Blender V2.61 - r43446

readfile.c

Go to the documentation of this file.
00001 /*
00002  * ***** BEGIN GPL LICENSE BLOCK *****
00003  *
00004  * This program is free software; you can redistribute it and/or
00005  * modify it under the terms of the GNU General Public License
00006  * as published by the Free Software Foundation; either version 2
00007  * of the License, or (at your option) any later version.
00008  *
00009  * This program is distributed in the hope that it will be useful,
00010  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00011  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00012  * GNU General Public License for more details.
00013  *
00014  * You should have received a copy of the GNU General Public License
00015  * along with this program; if not, write to the Free Software Foundation,
00016  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
00017  *
00018  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
00019  * All rights reserved.
00020  *
00021  *
00022  * Contributor(s): Blender Foundation
00023  *
00024  * ***** END GPL LICENSE BLOCK *****
00025  *
00026  */
00027 
00033 #include "zlib.h"
00034 
00035 #include <limits.h>
00036 #include <stdio.h> // for printf fopen fwrite fclose sprintf FILE
00037 #include <stdlib.h> // for getenv atoi
00038 #include <stddef.h> // for offsetof
00039 #include <fcntl.h> // for open
00040 #include <string.h> // for strrchr strncmp strstr
00041 #include <math.h> // for fabs
00042 #include <stdarg.h> /* for va_start/end */
00043 
00044 #ifndef WIN32
00045     #include <unistd.h> // for read close
00046 #else
00047     #include <io.h> // for open close read
00048 #include "winsock2.h"
00049 #include "BLI_winstuff.h"
00050 #endif
00051 
00052 /* allow readfile to use deprecated functionality */
00053 #define DNA_DEPRECATED_ALLOW
00054 
00055 #include "DNA_anim_types.h"
00056 #include "DNA_armature_types.h"
00057 #include "DNA_actuator_types.h"
00058 #include "DNA_brush_types.h"
00059 #include "DNA_camera_types.h"
00060 #include "DNA_cloth_types.h"
00061 #include "DNA_controller_types.h"
00062 #include "DNA_constraint_types.h"
00063 #include "DNA_dynamicpaint_types.h"
00064 #include "DNA_effect_types.h"
00065 #include "DNA_fileglobal_types.h"
00066 #include "DNA_genfile.h"
00067 #include "DNA_group_types.h"
00068 #include "DNA_gpencil_types.h"
00069 #include "DNA_ipo_types.h"
00070 #include "DNA_key_types.h"
00071 #include "DNA_lattice_types.h"
00072 #include "DNA_lamp_types.h"
00073 #include "DNA_meta_types.h"
00074 #include "DNA_material_types.h"
00075 #include "DNA_mesh_types.h"
00076 #include "DNA_meshdata_types.h"
00077 #include "DNA_nla_types.h"
00078 #include "DNA_node_types.h"
00079 #include "DNA_object_fluidsim.h" // NT
00080 #include "DNA_packedFile_types.h"
00081 #include "DNA_particle_types.h"
00082 #include "DNA_property_types.h"
00083 #include "DNA_text_types.h"
00084 #include "DNA_view3d_types.h"
00085 #include "DNA_screen_types.h"
00086 #include "DNA_sensor_types.h"
00087 #include "DNA_sdna_types.h"
00088 #include "DNA_scene_types.h"
00089 #include "DNA_sequence_types.h"
00090 #include "DNA_smoke_types.h"
00091 #include "DNA_speaker_types.h"
00092 #include "DNA_sound_types.h"
00093 #include "DNA_space_types.h"
00094 #include "DNA_vfont_types.h"
00095 #include "DNA_world_types.h"
00096 #include "DNA_movieclip_types.h"
00097 
00098 #include "MEM_guardedalloc.h"
00099 
00100 #include "BLI_blenlib.h"
00101 #include "BLI_math.h"
00102 #include "BLI_utildefines.h"
00103 
00104 #include "BKE_anim.h"
00105 #include "BKE_action.h"
00106 #include "BKE_armature.h"
00107 #include "BKE_brush.h"
00108 #include "BKE_colortools.h"
00109 #include "BKE_constraint.h"
00110 #include "BKE_context.h"
00111 #include "BKE_curve.h"
00112 #include "BKE_deform.h"
00113 #include "BKE_effect.h"
00114 #include "BKE_fcurve.h"
00115 #include "BKE_global.h" // for G
00116 #include "BKE_group.h"
00117 #include "BKE_image.h"
00118 #include "BKE_lattice.h"
00119 #include "BKE_library.h" // for which_libbase
00120 #include "BKE_idcode.h"
00121 #include "BKE_material.h"
00122 #include "BKE_main.h" // for Main
00123 #include "BKE_mesh.h" // for ME_ defines (patching)
00124 #include "BKE_modifier.h"
00125 #include "BKE_multires.h"
00126 #include "BKE_node.h" // for tree type defines
00127 #include "BKE_ocean.h"
00128 #include "BKE_object.h"
00129 #include "BKE_paint.h"
00130 #include "BKE_particle.h"
00131 #include "BKE_pointcache.h"
00132 #include "BKE_property.h" // for get_ob_property
00133 #include "BKE_report.h"
00134 #include "BKE_sca.h" // for init_actuator
00135 #include "BKE_scene.h"
00136 #include "BKE_screen.h"
00137 #include "BKE_sequencer.h"
00138 #include "BKE_text.h" // for txt_extended_ascii_as_utf8
00139 #include "BKE_texture.h" // for open_plugin_tex
00140 #include "BKE_tracking.h"
00141 #include "BKE_utildefines.h" // SWITCH_INT DATA ENDB DNA1 O_BINARY GLOB USER TEST REND
00142 #include "BKE_sound.h"
00143 
00144 #include "IMB_imbuf.h"  // for proxy / timecode versioning stuff
00145 
00146 #include "NOD_socket.h"
00147 
00148 //XXX #include "BIF_butspace.h" // badlevel, for do_versions, patching event codes
00149 //XXX #include "BIF_filelist.h" // badlevel too, where to move this? - elubie
00150 //XXX #include "BIF_previewrender.h" // bedlelvel, for struct RenderInfo
00151 #include "BLO_readfile.h"
00152 #include "BLO_undofile.h"
00153 
00154 #include "RE_engine.h"
00155 
00156 #include "readfile.h"
00157 
00158 #include "PIL_time.h"
00159 
00160 #include <errno.h>
00161 
00162 /*
00163  Remark: still a weak point is the newaddress() function, that doesnt solve reading from
00164  multiple files at the same time
00165 
00166  (added remark: oh, i thought that was solved? will look at that... (ton)
00167 
00168 READ
00169 - Existing Library (Main) push or free
00170 - allocate new Main
00171 - load file
00172 - read SDNA
00173 - for each LibBlock
00174     - read LibBlock
00175     - if a Library
00176         - make a new Main
00177         - attach ID's to it
00178     - else
00179         - read associated 'direct data'
00180         - link direct data (internal and to LibBlock)
00181 - read FileGlobal
00182 - read USER data, only when indicated (file is ~/X.XX/startup.blend)
00183 - free file
00184 - per Library (per Main)
00185     - read file
00186     - read SDNA
00187     - find LibBlocks and attach IDs to Main
00188         - if external LibBlock
00189             - search all Main's
00190                 - or it's already read,
00191                 - or not read yet
00192                 - or make new Main
00193     - per LibBlock
00194         - read recursive
00195         - read associated direct data
00196         - link direct data (internal and to LibBlock)
00197     - free file
00198 - per Library with unread LibBlocks
00199     - read file
00200     - read SDNA
00201     - per LibBlock
00202                - read recursive
00203                - read associated direct data
00204                - link direct data (internal and to LibBlock)
00205         - free file
00206 - join all Mains
00207 - link all LibBlocks and indirect pointers to libblocks
00208 - initialize FileGlobal and copy pointers to Global
00209 */
00210 
00211 /* also occurs in library.c */
00212 /* GS reads the memory pointed at in a specific ordering. There are,
00213  * however two definitions for it. I have jotted them down here, both,
00214  * but I think the first one is actually used. The thing is that
00215  * big-endian systems might read this the wrong way round. OTOH, we
00216  * constructed the IDs that are read out with this macro explicitly as
00217  * well. I expect we'll sort it out soon... */
00218 
00219 /* from blendef: */
00220 #define GS(a)   (*((short *)(a)))
00221 
00222 /* from misc_util: flip the bytes from x  */
00223 /*  #define GS(x) (((unsigned char *)(x))[0] << 8 | ((unsigned char *)(x))[1]) */
00224 
00225 // only used here in readfile.c
00226 #define SWITCH_LONGINT(a) { \
00227     char s_i, *p_i; \
00228     p_i= (char *)&(a);  \
00229     s_i=p_i[0]; p_i[0]=p_i[7]; p_i[7]=s_i; \
00230     s_i=p_i[1]; p_i[1]=p_i[6]; p_i[6]=s_i; \
00231     s_i=p_i[2]; p_i[2]=p_i[5]; p_i[5]=s_i; \
00232     s_i=p_i[3]; p_i[3]=p_i[4]; p_i[4]=s_i; }
00233 
00234 /***/
00235 
00236 typedef struct OldNew {
00237     void *old, *newp;
00238     int nr;
00239 } OldNew;
00240 
00241 typedef struct OldNewMap {
00242     OldNew *entries;
00243     int nentries, entriessize;
00244     int sorted;
00245     int lasthit;
00246 } OldNewMap;
00247 
00248 
00249 /* local prototypes */
00250 static void *read_struct(FileData *fd, BHead *bh, const char *blockname);
00251 static void direct_link_modifiers(FileData *fd, ListBase *lb);
00252 static void convert_tface_mt(FileData *fd, Main *main);
00253 
00254 /* this function ensures that reports are printed,
00255  * in the case of libraray linking errors this is important!
00256  *
00257  * bit kludge but better then doubling up on prints,
00258  * we could alternatively have a versions of a report function which foces printing - campbell
00259  */
00260 static void BKE_reportf_wrap(ReportList *reports, ReportType type, const char *format, ...)
00261 {
00262     char fixed_buf[1024]; /* should be long enough */
00263 
00264     va_list args;
00265 
00266     va_start(args, format);
00267     vsnprintf(fixed_buf, sizeof(fixed_buf), format, args);
00268     va_end(args);
00269 
00270     fixed_buf[sizeof(fixed_buf) - 1] = '\0';
00271 
00272     BKE_report(reports, type, fixed_buf);
00273 
00274     if(G.background==0) {
00275         printf("%s\n", fixed_buf);
00276     }
00277 }
00278 
00279 static OldNewMap *oldnewmap_new(void) 
00280 {
00281     OldNewMap *onm= MEM_callocN(sizeof(*onm), "OldNewMap");
00282     
00283     onm->entriessize= 1024;
00284     onm->entries= MEM_mallocN(sizeof(*onm->entries)*onm->entriessize, "OldNewMap.entries");
00285     
00286     return onm;
00287 }
00288 
00289 static int verg_oldnewmap(const void *v1, const void *v2)
00290 {
00291     const struct OldNew *x1=v1, *x2=v2;
00292     
00293     if( x1->old > x2->old) return 1;
00294     else if( x1->old < x2->old) return -1;
00295     return 0;
00296 }
00297 
00298 
00299 static void oldnewmap_sort(FileData *fd) 
00300 {
00301     qsort(fd->libmap->entries, fd->libmap->nentries, sizeof(OldNew), verg_oldnewmap);
00302     fd->libmap->sorted= 1;
00303 }
00304 
00305 /* nr is zero for data, and ID code for libdata */
00306 static void oldnewmap_insert(OldNewMap *onm, void *oldaddr, void *newaddr, int nr) 
00307 {
00308     OldNew *entry;
00309 
00310     if(oldaddr==NULL || newaddr==NULL) return;
00311     
00312     if (onm->nentries==onm->entriessize) {
00313         int osize= onm->entriessize;
00314         OldNew *oentries= onm->entries;
00315 
00316         onm->entriessize*= 2;
00317         onm->entries= MEM_mallocN(sizeof(*onm->entries)*onm->entriessize, "OldNewMap.entries");
00318 
00319         memcpy(onm->entries, oentries, sizeof(*oentries)*osize);
00320         MEM_freeN(oentries);
00321     }
00322 
00323     entry= &onm->entries[onm->nentries++];
00324     entry->old= oldaddr;
00325     entry->newp= newaddr;
00326     entry->nr= nr;
00327 }
00328 
00329 static void *oldnewmap_lookup_and_inc(OldNewMap *onm, void *addr) 
00330 {
00331     int i;
00332 
00333     if(addr==NULL) return NULL;
00334 
00335     if (onm->lasthit<onm->nentries-1) {
00336         OldNew *entry= &onm->entries[++onm->lasthit];
00337 
00338         if (entry->old==addr) {
00339             entry->nr++;
00340             return entry->newp;
00341         }
00342     }
00343 
00344     for (i=0; i<onm->nentries; i++) {
00345         OldNew *entry= &onm->entries[i];
00346 
00347         if (entry->old==addr) {
00348             onm->lasthit= i;
00349 
00350             entry->nr++;
00351             return entry->newp;
00352         }
00353     }
00354 
00355     return NULL;
00356 }
00357 
00358 /* for libdata, nr has ID code, no increment */
00359 static void *oldnewmap_liblookup(OldNewMap *onm, void *addr, void *lib) 
00360 {
00361     int i;
00362     
00363     if(addr==NULL) return NULL;
00364     
00365     /* lasthit works fine for non-libdata, linking there is done in same sequence as writing */
00366     if(onm->sorted) {
00367         OldNew entry_s, *entry;
00368         
00369         entry_s.old= addr;
00370         
00371         entry= bsearch(&entry_s, onm->entries, onm->nentries, sizeof(OldNew), verg_oldnewmap);
00372         if(entry) {
00373             ID *id= entry->newp;
00374             
00375             if (id && (!lib || id->lib)) {
00376                 return entry->newp;
00377             }
00378         }
00379     }
00380     
00381     for (i=0; i<onm->nentries; i++) {
00382         OldNew *entry= &onm->entries[i];
00383 
00384         if (entry->old==addr) {
00385             ID *id= entry->newp;
00386 
00387             if (id && (!lib || id->lib)) {
00388                 return entry->newp;
00389             }
00390         }
00391     }
00392 
00393     return NULL;
00394 }
00395 
00396 static void oldnewmap_free_unused(OldNewMap *onm) 
00397 {
00398     int i;
00399 
00400     for (i=0; i<onm->nentries; i++) {
00401         OldNew *entry= &onm->entries[i];
00402         if (entry->nr==0) {
00403             MEM_freeN(entry->newp);
00404             entry->newp= NULL;
00405         }
00406     }
00407 }
00408 
00409 static void oldnewmap_clear(OldNewMap *onm) 
00410 {
00411     onm->nentries= 0;
00412     onm->lasthit= 0;
00413 }
00414 
00415 static void oldnewmap_free(OldNewMap *onm) 
00416 {
00417     MEM_freeN(onm->entries);
00418     MEM_freeN(onm);
00419 }
00420 
00421 /***/
00422 
00423 static void read_libraries(FileData *basefd, ListBase *mainlist);
00424 
00425 /* ************ help functions ***************** */
00426 
00427 static void add_main_to_main(Main *mainvar, Main *from)
00428 {
00429     ListBase *lbarray[MAX_LIBARRAY], *fromarray[MAX_LIBARRAY];
00430     int a;
00431 
00432     set_listbasepointers(mainvar, lbarray);
00433     a= set_listbasepointers(from, fromarray);
00434     while(a--) {
00435         BLI_movelisttolist(lbarray[a], fromarray[a]);
00436     }
00437 }
00438 
00439 void blo_join_main(ListBase *mainlist)
00440 {
00441     Main *tojoin, *mainl;
00442     
00443     
00444     mainl= mainlist->first;
00445     while ((tojoin= mainl->next)) {
00446         add_main_to_main(mainl, tojoin);
00447         BLI_remlink(mainlist, tojoin);
00448         MEM_freeN(tojoin);
00449     }
00450 }
00451 
00452 static void split_libdata(ListBase *lb, Main *first)
00453 {
00454     ListBase *lbn;
00455     ID *id, *idnext;
00456     Main *mainvar;
00457 
00458     id= lb->first;
00459     while(id) {
00460         idnext= id->next;
00461         if(id->lib) {
00462             mainvar= first;
00463             while(mainvar) {
00464                 if(mainvar->curlib==id->lib) {
00465                     lbn= which_libbase(mainvar, GS(id->name));
00466                     BLI_remlink(lb, id);
00467                     BLI_addtail(lbn, id);
00468                     break;
00469                 }
00470                 mainvar= mainvar->next;
00471             }
00472             if(mainvar==NULL) printf("error split_libdata\n");
00473         }
00474         id= idnext;
00475     }
00476 }
00477 
00478 void blo_split_main(ListBase *mainlist, Main *main)
00479 {
00480     ListBase *lbarray[MAX_LIBARRAY];
00481     Library *lib;
00482     int i;
00483 
00484     mainlist->first= mainlist->last= main;
00485     main->next= NULL;
00486 
00487     if(main->library.first==NULL)
00488         return;
00489     
00490     for (lib= main->library.first; lib; lib= lib->id.next) {
00491         Main *libmain= MEM_callocN(sizeof(Main), "libmain");
00492         libmain->curlib= lib;
00493         BLI_addtail(mainlist, libmain);
00494     }
00495 
00496     i= set_listbasepointers(main, lbarray);
00497     while(i--)
00498         split_libdata(lbarray[i], main->next);
00499 }
00500 
00501 /* removes things like /blah/blah/../../blah/ etc, then writes in *name the full path */
00502 static void cleanup_path(const char *relabase, char *name)
00503 {
00504     char filename[FILE_MAXFILE];
00505     
00506     BLI_splitdirstring(name, filename);
00507     BLI_cleanup_dir(relabase, name);
00508     strcat(name, filename);
00509 }
00510 
00511 static void read_file_version(FileData *fd, Main *main)
00512 {
00513     BHead *bhead;
00514     
00515     for (bhead= blo_firstbhead(fd); bhead; bhead= blo_nextbhead(fd, bhead)) {
00516         if (bhead->code==GLOB) {
00517             FileGlobal *fg= read_struct(fd, bhead, "Global");
00518             if(fg) {
00519                 main->subversionfile= fg->subversion;
00520                 main->minversionfile= fg->minversion;
00521                 main->minsubversionfile= fg->minsubversion;
00522                 MEM_freeN(fg);
00523             }
00524             else if (bhead->code==ENDB)
00525                 break;
00526         }
00527     }
00528 }
00529 
00530 
00531 static Main *blo_find_main(FileData *fd, ListBase *mainlist, const char *filepath, const char *relabase)
00532 {
00533     Main *m;
00534     Library *lib;
00535     char name1[FILE_MAX];
00536     
00537     BLI_strncpy(name1, filepath, sizeof(name1));
00538     cleanup_path(relabase, name1);
00539 //  printf("blo_find_main: original in  %s\n", name);
00540 //  printf("blo_find_main: converted to %s\n", name1);
00541 
00542     for (m= mainlist->first; m; m= m->next) {
00543         char *libname= (m->curlib)?m->curlib->filepath:m->name;
00544         
00545         if (BLI_path_cmp(name1, libname) == 0) {
00546             if(G.f & G_DEBUG) printf("blo_find_main: found library %s\n", libname);
00547             return m;
00548         }
00549     }
00550 
00551     m= MEM_callocN(sizeof(Main), "find_main");
00552     BLI_addtail(mainlist, m);
00553 
00554     lib= alloc_libblock(&m->library, ID_LI, "lib");
00555     BLI_strncpy(lib->name, filepath, sizeof(lib->name));
00556     BLI_strncpy(lib->filepath, name1, sizeof(lib->filepath));
00557     
00558     m->curlib= lib;
00559     
00560     read_file_version(fd, m);
00561     
00562     if(G.f & G_DEBUG) printf("blo_find_main: added new lib %s\n", filepath);
00563     return m;
00564 }
00565 
00566 
00567 /* ************ FILE PARSING ****************** */
00568 
00569 static void switch_endian_bh4(BHead4 *bhead)
00570 {
00571     /* the ID_.. codes */
00572     if((bhead->code & 0xFFFF)==0) bhead->code >>=16;
00573 
00574     if (bhead->code != ENDB) {
00575         SWITCH_INT(bhead->len);
00576         SWITCH_INT(bhead->SDNAnr);
00577         SWITCH_INT(bhead->nr);
00578     }
00579 }
00580 
00581 static void switch_endian_bh8(BHead8 *bhead)
00582 {
00583     /* the ID_.. codes */
00584     if((bhead->code & 0xFFFF)==0) bhead->code >>=16;
00585 
00586     if (bhead->code != ENDB) {
00587         SWITCH_INT(bhead->len);
00588         SWITCH_INT(bhead->SDNAnr);
00589         SWITCH_INT(bhead->nr);
00590     }
00591 }
00592 
00593 static void bh4_from_bh8(BHead *bhead, BHead8 *bhead8, int do_endian_swap)
00594 {
00595     BHead4 *bhead4 = (BHead4 *) bhead;
00596 #if defined(WIN32) && !defined(FREE_WINDOWS)
00597     __int64 old;
00598 #else
00599     long long old;
00600 #endif
00601 
00602     bhead4->code= bhead8->code;
00603     bhead4->len= bhead8->len;
00604 
00605     if (bhead4->code != ENDB) {
00606 
00607         //perform a endian swap on 64bit pointers, otherwise the pointer might map to zero
00608         //0x0000000000000000000012345678 would become 0x12345678000000000000000000000000
00609         if (do_endian_swap) {
00610             SWITCH_LONGINT(bhead8->old);
00611         }
00612 
00613         /* this patch is to avoid a long long being read from not-eight aligned positions
00614            is necessary on any modern 64bit architecture) */
00615         memcpy(&old, &bhead8->old, 8);
00616         bhead4->old = (int) (old >> 3);
00617 
00618         bhead4->SDNAnr= bhead8->SDNAnr;
00619         bhead4->nr= bhead8->nr;
00620     }
00621 }
00622 
00623 static void bh8_from_bh4(BHead *bhead, BHead4 *bhead4)
00624 {
00625     BHead8 *bhead8 = (BHead8 *) bhead;
00626 
00627     bhead8->code= bhead4->code;
00628     bhead8->len= bhead4->len;
00629 
00630     if (bhead8->code != ENDB) {
00631         bhead8->old= bhead4->old;
00632         bhead8->SDNAnr= bhead4->SDNAnr;
00633         bhead8->nr= bhead4->nr;
00634     }
00635 }
00636 
00637 static BHeadN *get_bhead(FileData *fd)
00638 {
00639     BHeadN *new_bhead = NULL;
00640     int readsize;
00641     
00642     if (fd) {
00643         if ( ! fd->eof) {
00644             /* initializing to zero isn't strictly needed but shuts valgrind up
00645              * since uninitialized memory gets compared */
00646             BHead8 bhead8= {0};
00647             BHead4 bhead4= {0};
00648             BHead  bhead= {0};
00649             
00650             // First read the bhead structure.
00651             // Depending on the platform the file was written on this can
00652             // be a big or little endian BHead4 or BHead8 structure.
00653 
00654             // As usual 'ENDB' (the last *partial* bhead of the file)
00655             // needs some special handling. We don't want to EOF just yet.
00656 
00657             if (fd->flags & FD_FLAGS_FILE_POINTSIZE_IS_4) {
00658                 bhead4.code = DATA;
00659                 readsize = fd->read(fd, &bhead4, sizeof(bhead4));
00660 
00661                 if (readsize == sizeof(bhead4) || bhead4.code == ENDB) {
00662                     if (fd->flags & FD_FLAGS_SWITCH_ENDIAN) {
00663                         switch_endian_bh4(&bhead4);
00664                     }
00665 
00666                     if (fd->flags & FD_FLAGS_POINTSIZE_DIFFERS) {
00667                         bh8_from_bh4(&bhead, &bhead4);
00668                     } else {
00669                         memcpy(&bhead, &bhead4, sizeof(bhead));
00670                     }
00671                 } else {
00672                     fd->eof = 1;
00673                     bhead.len= 0;
00674                 }
00675             } else {
00676                 bhead8.code = DATA;
00677                 readsize = fd->read(fd, &bhead8, sizeof(bhead8));
00678 
00679                 if (readsize == sizeof(bhead8) || bhead8.code == ENDB) {
00680                     if (fd->flags & FD_FLAGS_SWITCH_ENDIAN) {
00681                         switch_endian_bh8(&bhead8);
00682                     }
00683 
00684                     if (fd->flags & FD_FLAGS_POINTSIZE_DIFFERS) {
00685                         bh4_from_bh8(&bhead, &bhead8, (fd->flags & FD_FLAGS_SWITCH_ENDIAN));
00686                     } else {
00687                         memcpy(&bhead, &bhead8, sizeof(bhead));
00688                     }
00689                 } else {
00690                     fd->eof = 1;
00691                     bhead.len= 0;
00692                 }
00693             }
00694 
00695             /* make sure people are not trying to pass bad blend files */
00696             if (bhead.len < 0) fd->eof = 1;
00697 
00698             // bhead now contains the (converted) bhead structure. Now read
00699             // the associated data and put everything in a BHeadN (creative naming !)
00700 
00701             if ( ! fd->eof) {
00702                 new_bhead = MEM_mallocN(sizeof(BHeadN) + bhead.len, "new_bhead");
00703                 if (new_bhead) {
00704                     new_bhead->next = new_bhead->prev = NULL;
00705                     new_bhead->bhead = bhead;
00706 
00707                     readsize = fd->read(fd, new_bhead + 1, bhead.len);
00708 
00709                     if (readsize != bhead.len) {
00710                         fd->eof = 1;
00711                         MEM_freeN(new_bhead);
00712                         new_bhead = NULL;
00713                     }
00714                 } else {
00715                     fd->eof = 1;
00716                 }
00717             }
00718         }
00719     }
00720 
00721     // We've read a new block. Now add it to the list
00722     // of blocks.
00723 
00724     if (new_bhead) {
00725         BLI_addtail(&fd->listbase, new_bhead);
00726     }
00727 
00728     return(new_bhead);
00729 }
00730 
00731 BHead *blo_firstbhead(FileData *fd)
00732 {
00733     BHeadN *new_bhead;
00734     BHead *bhead = NULL;
00735 
00736     // Rewind the file
00737     // Read in a new block if necessary
00738 
00739     new_bhead = fd->listbase.first;
00740     if (new_bhead == NULL) {
00741         new_bhead = get_bhead(fd);
00742     }
00743 
00744     if (new_bhead) {
00745         bhead = &new_bhead->bhead;
00746     }
00747 
00748     return(bhead);
00749 }
00750 
00751 BHead *blo_prevbhead(FileData *UNUSED(fd), BHead *thisblock)
00752 {
00753     BHeadN *bheadn= (BHeadN *) (((char *) thisblock) - GET_INT_FROM_POINTER( &((BHeadN*)0)->bhead) );
00754     BHeadN *prev= bheadn->prev;
00755 
00756     return prev?&prev->bhead:NULL;
00757 }
00758 
00759 BHead *blo_nextbhead(FileData *fd, BHead *thisblock)
00760 {
00761     BHeadN *new_bhead = NULL;
00762     BHead *bhead = NULL;
00763 
00764     if (thisblock) {
00765         // bhead is actually a sub part of BHeadN
00766         // We calculate the BHeadN pointer from the BHead pointer below
00767         new_bhead = (BHeadN *) (((char *) thisblock) - GET_INT_FROM_POINTER( &((BHeadN*)0)->bhead) );
00768 
00769         // get the next BHeadN. If it doesn't exist we read in the next one
00770         new_bhead = new_bhead->next;
00771         if (new_bhead == NULL) {
00772             new_bhead = get_bhead(fd);
00773         }
00774     }
00775 
00776     if (new_bhead) {
00777         // here we do the reverse:
00778         // go from the BHeadN pointer to the BHead pointer
00779         bhead = &new_bhead->bhead;
00780     }
00781 
00782     return(bhead);
00783 }
00784 
00785 static void decode_blender_header(FileData *fd)
00786 {
00787     char header[SIZEOFBLENDERHEADER], num[4];
00788     int readsize;
00789 
00790     // read in the header data
00791     readsize = fd->read(fd, header, sizeof(header));
00792 
00793     if (readsize == sizeof(header)) {
00794         if(strncmp(header, "BLENDER", 7) == 0) {
00795             int remove_this_endian_test= 1;
00796 
00797             fd->flags |= FD_FLAGS_FILE_OK;
00798 
00799             // what size are pointers in the file ?
00800             if(header[7]=='_') {
00801                 fd->flags |= FD_FLAGS_FILE_POINTSIZE_IS_4;
00802                 if (sizeof(void *) != 4) {
00803                     fd->flags |= FD_FLAGS_POINTSIZE_DIFFERS;
00804                 }
00805             } else {
00806                 if (sizeof(void *) != 8) {
00807                     fd->flags |= FD_FLAGS_POINTSIZE_DIFFERS;
00808                 }
00809             }
00810 
00811             // is the file saved in a different endian
00812             // than we need ?
00813             if (((((char*)&remove_this_endian_test)[0]==1)?L_ENDIAN:B_ENDIAN) != ((header[8]=='v')?L_ENDIAN:B_ENDIAN)) {
00814                 fd->flags |= FD_FLAGS_SWITCH_ENDIAN;
00815             }
00816 
00817             // get the version number
00818 
00819             memcpy(num, header+9, 3);
00820             num[3] = 0;
00821             fd->fileversion = atoi(num);
00822         }
00823     }
00824 }
00825 
00826 static int read_file_dna(FileData *fd)
00827 {
00828     BHead *bhead;
00829 
00830     for (bhead= blo_firstbhead(fd); bhead; bhead= blo_nextbhead(fd, bhead)) {
00831         if (bhead->code==DNA1) {
00832             int do_endian_swap= (fd->flags&FD_FLAGS_SWITCH_ENDIAN)?1:0;
00833 
00834             fd->filesdna= DNA_sdna_from_data(&bhead[1], bhead->len, do_endian_swap);
00835             if (fd->filesdna) {
00836                 
00837                 fd->compflags= DNA_struct_get_compareflags(fd->filesdna, fd->memsdna);
00838                 /* used to retrieve ID names from (bhead+1) */
00839                 fd->id_name_offs= DNA_elem_offset(fd->filesdna, "ID", "char", "name[]");
00840             }
00841 
00842             return 1;
00843         } else if (bhead->code==ENDB)
00844             break;
00845     }
00846 
00847     return 0;
00848 }
00849 
00850 static int fd_read_from_file(FileData *filedata, void *buffer, unsigned int size)
00851 {
00852     int readsize = read(filedata->filedes, buffer, size);
00853 
00854     if (readsize < 0) {
00855         readsize = EOF;
00856     } else {
00857         filedata->seek += readsize;
00858     }
00859 
00860     return (readsize);
00861 }
00862 
00863 static int fd_read_gzip_from_file(FileData *filedata, void *buffer, unsigned int size)
00864 {
00865     int readsize = gzread(filedata->gzfiledes, buffer, size);
00866 
00867     if (readsize < 0) {
00868         readsize = EOF;
00869     } else {
00870         filedata->seek += readsize;
00871     }
00872 
00873     return (readsize);
00874 }
00875 
00876 static int fd_read_from_memory(FileData *filedata, void *buffer, unsigned int size)
00877 {
00878     // don't read more bytes then there are available in the buffer
00879     int readsize = (int)MIN2(size, (unsigned int)(filedata->buffersize - filedata->seek));
00880 
00881     memcpy(buffer, filedata->buffer + filedata->seek, readsize);
00882     filedata->seek += readsize;
00883 
00884     return (readsize);
00885 }
00886 
00887 static int fd_read_from_memfile(FileData *filedata, void *buffer, unsigned int size)
00888 {
00889     static unsigned int seek= 1<<30;    /* the current position */
00890     static unsigned int offset= 0;      /* size of previous chunks */
00891     static MemFileChunk *chunk=NULL;
00892     unsigned int chunkoffset, readsize, totread;
00893     
00894     if(size==0) return 0;
00895     
00896     if(seek != (unsigned int)filedata->seek) {
00897         chunk= filedata->memfile->chunks.first;
00898         seek= 0;
00899         
00900         while(chunk) {
00901             if(seek + chunk->size > (unsigned) filedata->seek) break;
00902             seek+= chunk->size;
00903             chunk= chunk->next;
00904         }
00905         offset= seek;
00906         seek= filedata->seek;
00907     }
00908     
00909     if(chunk) {
00910         totread= 0;
00911 
00912         do {
00913             /* first check if it's on the end if current chunk */
00914             if(seek-offset == chunk->size) {
00915                 offset+= chunk->size;
00916                 chunk= chunk->next;
00917             }
00918 
00919             /* debug, should never happen */
00920             if(chunk==NULL) {
00921                 printf("illegal read, chunk zero\n");
00922                 return 0;
00923             }
00924 
00925             chunkoffset= seek-offset;
00926             readsize= size-totread;
00927 
00928             /* data can be spread over multiple chunks, so clamp size
00929              * to within this chunk, and then it will read further in
00930              * the next chunk */
00931             if(chunkoffset+readsize > chunk->size)
00932                 readsize= chunk->size-chunkoffset;
00933 
00934             memcpy((char*)buffer+totread, chunk->buf+chunkoffset, readsize);
00935             totread += readsize;
00936             filedata->seek += readsize;
00937             seek += readsize;
00938         } while(totread < size);
00939         
00940         return totread;
00941     }
00942 
00943     return 0;
00944 }
00945 
00946 static FileData *filedata_new(void)
00947 {
00948     FileData *fd = MEM_callocN(sizeof(FileData), "FileData");
00949 
00950     fd->filedes = -1;
00951     fd->gzfiledes = NULL;
00952 
00953         /* XXX, this doesn't need to be done all the time,
00954          * but it keeps us reentrant,  remove once we have
00955          * a lib that provides a nice lock. - zr
00956          */
00957     fd->memsdna = DNA_sdna_from_data(DNAstr,  DNAlen,  0);
00958 
00959     fd->datamap = oldnewmap_new();
00960     fd->globmap = oldnewmap_new();
00961     fd->libmap = oldnewmap_new();
00962 
00963     return fd;
00964 }
00965 
00966 static FileData *blo_decode_and_check(FileData *fd, ReportList *reports)
00967 {
00968     decode_blender_header(fd);
00969 
00970     if (fd->flags & FD_FLAGS_FILE_OK) {
00971         if (!read_file_dna(fd)) {
00972             BKE_reportf(reports, RPT_ERROR, "Failed to read blend file: \"%s\", incomplete", fd->relabase);
00973             blo_freefiledata(fd);
00974             fd= NULL;
00975         }
00976     } 
00977     else {
00978         BKE_reportf(reports, RPT_ERROR, "Failed to read blend file: \"%s\", not a blend file", fd->relabase);
00979         blo_freefiledata(fd);
00980         fd= NULL;
00981     }
00982 
00983     return fd;
00984 }
00985 
00986 /* cannot be called with relative paths anymore! */
00987 /* on each new library added, it now checks for the current FileData and expands relativeness */
00988 FileData *blo_openblenderfile(const char *filepath, ReportList *reports)
00989 {
00990     gzFile gzfile;
00991     errno= 0;
00992     gzfile= gzopen(filepath, "rb");
00993 
00994     if (gzfile == (gzFile)Z_NULL) {
00995         BKE_reportf(reports, RPT_ERROR, "Unable to open \"%s\": %s.", filepath, errno ? strerror(errno) : "Unknown error reading file");
00996         return NULL;
00997     } else {
00998         FileData *fd = filedata_new();
00999         fd->gzfiledes = gzfile;
01000         fd->read = fd_read_gzip_from_file;
01001 
01002         /* needed for library_append and read_libraries */
01003         BLI_strncpy(fd->relabase, filepath, sizeof(fd->relabase));
01004 
01005         return blo_decode_and_check(fd, reports);
01006     }
01007 }
01008 
01009 FileData *blo_openblendermemory(void *mem, int memsize, ReportList *reports)
01010 {
01011     if (!mem || memsize<SIZEOFBLENDERHEADER) {
01012         BKE_report(reports, RPT_ERROR, (mem)? "Unable to read": "Unable to open");
01013         return NULL;
01014     } else {
01015         FileData *fd= filedata_new();
01016         fd->buffer= mem;
01017         fd->buffersize= memsize;
01018         fd->read= fd_read_from_memory;
01019         fd->flags|= FD_FLAGS_NOT_MY_BUFFER;
01020 
01021         return blo_decode_and_check(fd, reports);
01022     }
01023 }
01024 
01025 FileData *blo_openblendermemfile(MemFile *memfile, ReportList *reports)
01026 {
01027     if (!memfile) {
01028         BKE_report(reports, RPT_ERROR, "Unable to open blend <memory>");
01029         return NULL;
01030     } else {
01031         FileData *fd= filedata_new();
01032         fd->memfile= memfile;
01033 
01034         fd->read= fd_read_from_memfile;
01035         fd->flags|= FD_FLAGS_NOT_MY_BUFFER;
01036 
01037         return blo_decode_and_check(fd, reports);
01038     }
01039 }
01040 
01041 
01042 void blo_freefiledata(FileData *fd)
01043 {
01044     if (fd) {
01045         
01046         if (fd->filedes != -1) {
01047             close(fd->filedes);
01048         }
01049 
01050         if (fd->gzfiledes != NULL)
01051         {
01052             gzclose(fd->gzfiledes);
01053         }
01054 
01055         if (fd->buffer && !(fd->flags & FD_FLAGS_NOT_MY_BUFFER)) {
01056             MEM_freeN(fd->buffer);
01057             fd->buffer = NULL;
01058         }
01059 
01060         // Free all BHeadN data blocks
01061         BLI_freelistN(&fd->listbase);
01062 
01063         if (fd->memsdna)
01064             DNA_sdna_free(fd->memsdna);
01065         if (fd->filesdna)
01066             DNA_sdna_free(fd->filesdna);
01067         if (fd->compflags)
01068             MEM_freeN(fd->compflags);
01069 
01070         if (fd->datamap)
01071             oldnewmap_free(fd->datamap);
01072         if (fd->globmap)
01073             oldnewmap_free(fd->globmap);
01074         if (fd->imamap)
01075             oldnewmap_free(fd->imamap);
01076         if (fd->movieclipmap)
01077             oldnewmap_free(fd->movieclipmap);
01078         if (fd->libmap && !(fd->flags & FD_FLAGS_NOT_MY_LIBMAP))
01079             oldnewmap_free(fd->libmap);
01080         if (fd->bheadmap)
01081             MEM_freeN(fd->bheadmap);
01082         
01083         MEM_freeN(fd);
01084     }
01085 }
01086 
01087 /* ************ DIV ****************** */
01088 
01089 int BLO_has_bfile_extension(const char *str)
01090 {
01091     return (BLI_testextensie(str, ".ble") || BLI_testextensie(str, ".blend") || BLI_testextensie(str, ".blend.gz"));
01092 }
01093 
01094 int BLO_is_a_library(const char *path, char *dir, char *group)
01095 {
01096     /* return ok when a blenderfile, in dir is the filename,
01097      * in group the type of libdata
01098      */
01099     int len;
01100     char *fd;
01101     
01102     strcpy(dir, path);
01103     len= strlen(dir);
01104     if(len<7) return 0;
01105     if( dir[len-1] != '/' && dir[len-1] != '\\') return 0;
01106     
01107     group[0]= 0;
01108     dir[len-1]= 0;
01109 
01110     /* Find the last slash */
01111     fd= BLI_last_slash(dir);
01112 
01113     if(fd==NULL) return 0;
01114     *fd= 0;
01115     if(BLO_has_bfile_extension(fd+1)) {
01116         /* the last part of the dir is a .blend file, no group follows */
01117         *fd= '/'; /* put back the removed slash separating the dir and the .blend file name */
01118     }
01119     else {      
01120         char *gp = fd+1; // in case we have a .blend file, gp points to the group
01121 
01122         /* Find the last slash */
01123         fd= BLI_last_slash(dir);
01124         if (!fd || !BLO_has_bfile_extension(fd+1)) return 0;
01125 
01126         /* now we know that we are in a blend file and it is safe to 
01127            assume that gp actually points to a group */
01128         if (strcmp("Screen", gp)!=0)
01129             BLI_strncpy(group, gp, GROUP_MAX);
01130     }
01131     return 1;
01132 }
01133 
01134 /* ************** OLD POINTERS ******************* */
01135 
01136 static void *newdataadr(FileData *fd, void *adr)        /* only direct databocks */
01137 {
01138     return oldnewmap_lookup_and_inc(fd->datamap, adr);
01139 }
01140 
01141 static void *newglobadr(FileData *fd, void *adr)        /* direct datablocks with global linking */
01142 {
01143     return oldnewmap_lookup_and_inc(fd->globmap, adr);
01144 }
01145 
01146 static void *newimaadr(FileData *fd, void *adr)     /* used to restore image data after undo */
01147 {
01148     if(fd->imamap && adr)
01149         return oldnewmap_lookup_and_inc(fd->imamap, adr);
01150     return NULL;
01151 }
01152 
01153 static void *newmclipadr(FileData *fd, void *adr)              /* used to restore movie clip data after undo */
01154 {
01155     if(fd->movieclipmap && adr)
01156         return oldnewmap_lookup_and_inc(fd->movieclipmap, adr);
01157     return NULL;
01158 }
01159 
01160 
01161 static void *newlibadr(FileData *fd, void *lib, void *adr)      /* only lib data */
01162 {
01163     return oldnewmap_liblookup(fd->libmap, adr, lib);
01164 }
01165 
01166 static void *newlibadr_us(FileData *fd, void *lib, void *adr)   /* increases user number */
01167 {
01168     ID *id= newlibadr(fd, lib, adr);
01169 
01170     if(id)
01171         id->us++;
01172 
01173     return id;
01174 }
01175 
01176 static void change_idid_adr_fd(FileData *fd, void *old, void *new)
01177 {
01178     int i;
01179     
01180     for (i=0; i<fd->libmap->nentries; i++) {
01181         OldNew *entry= &fd->libmap->entries[i];
01182         
01183         if (old==entry->newp && entry->nr==ID_ID) {
01184             entry->newp= new;
01185             if(new) entry->nr= GS( ((ID *)new)->name );
01186             break;
01187         }
01188     }
01189 }
01190 
01191 static void change_idid_adr(ListBase *mainlist, FileData *basefd, void *old, void *new)
01192 {
01193     Main *mainptr;
01194     
01195     for(mainptr= mainlist->first; mainptr; mainptr= mainptr->next) {
01196         FileData *fd;
01197         
01198         if(mainptr->curlib) fd= mainptr->curlib->filedata;
01199         else fd= basefd;
01200         
01201         if(fd) {
01202             change_idid_adr_fd(fd, old, new);
01203         }
01204     }
01205 }
01206 
01207 /* lib linked proxy objects point to our local data, we need
01208  * to clear that pointer before reading the undo memfile since
01209  * the object might be removed, it is set again in reading
01210  * if the local object still exists */
01211 void blo_clear_proxy_pointers_from_lib(Main *oldmain)
01212 {
01213     Object *ob= oldmain->object.first;
01214     
01215     for(;ob; ob= ob->id.next)
01216         if(ob->id.lib)
01217             ob->proxy_from= NULL;
01218 }
01219 
01220 void blo_make_image_pointer_map(FileData *fd, Main *oldmain)
01221 {
01222     Image *ima= oldmain->image.first;
01223     Scene *sce= oldmain->scene.first;
01224     int a;
01225     
01226     fd->imamap= oldnewmap_new();
01227     
01228     for(;ima; ima= ima->id.next) {
01229         Link *ibuf= ima->ibufs.first;
01230         for(; ibuf; ibuf= ibuf->next) 
01231             oldnewmap_insert(fd->imamap, ibuf, ibuf, 0);
01232         if(ima->gputexture)
01233             oldnewmap_insert(fd->imamap, ima->gputexture, ima->gputexture, 0);
01234         for(a=0; a<IMA_MAX_RENDER_SLOT; a++)
01235             if(ima->renders[a])
01236                 oldnewmap_insert(fd->imamap, ima->renders[a], ima->renders[a], 0);
01237     }
01238     for(; sce; sce= sce->id.next) {
01239         if(sce->nodetree) {
01240             bNode *node;
01241             for(node= sce->nodetree->nodes.first; node; node= node->next)
01242                 oldnewmap_insert(fd->imamap, node->preview, node->preview, 0);
01243         }
01244     }
01245 }
01246 
01247 /* set old main image ibufs to zero if it has been restored */
01248 /* this works because freeing old main only happens after this call */
01249 void blo_end_image_pointer_map(FileData *fd, Main *oldmain)
01250 {
01251     OldNew *entry= fd->imamap->entries;
01252     Image *ima= oldmain->image.first;
01253     Scene *sce= oldmain->scene.first;
01254     int i;
01255     
01256     /* used entries were restored, so we put them to zero */
01257     for (i=0; i<fd->imamap->nentries; i++, entry++) {
01258         if (entry->nr>0)
01259             entry->newp= NULL;
01260     }
01261     
01262     for(;ima; ima= ima->id.next) {
01263         Link *ibuf, *next;
01264         
01265         /* this mirrors direct_link_image */
01266         for(ibuf= ima->ibufs.first; ibuf; ibuf= next) {
01267             next= ibuf->next;
01268             if(NULL==newimaadr(fd, ibuf)) { /* so was restored */
01269                 BLI_remlink(&ima->ibufs, ibuf);
01270                 ima->bindcode= 0;
01271                 ima->gputexture= NULL;
01272             }
01273         }
01274         for(i=0; i<IMA_MAX_RENDER_SLOT; i++)
01275             ima->renders[i]= newimaadr(fd, ima->renders[i]);
01276 
01277         ima->gputexture= newimaadr(fd, ima->gputexture);
01278     }
01279     for(; sce; sce= sce->id.next) {
01280         if(sce->nodetree) {
01281             bNode *node;
01282             for(node= sce->nodetree->nodes.first; node; node= node->next)
01283                 node->preview= newimaadr(fd, node->preview);
01284         }
01285     }
01286 }
01287 
01288 void blo_make_movieclip_pointer_map(FileData *fd, Main *oldmain)
01289 {
01290     MovieClip *clip= oldmain->movieclip.first;
01291     Scene *sce= oldmain->scene.first;
01292 
01293     fd->movieclipmap= oldnewmap_new();
01294 
01295     for(;clip; clip= clip->id.next) {
01296         if(clip->cache)
01297             oldnewmap_insert(fd->movieclipmap, clip->cache, clip->cache, 0);
01298 
01299         if(clip->tracking.camera.intrinsics)
01300             oldnewmap_insert(fd->movieclipmap, clip->tracking.camera.intrinsics, clip->tracking.camera.intrinsics, 0);
01301     }
01302 
01303     for(; sce; sce= sce->id.next) {
01304         if(sce->nodetree) {
01305             bNode *node;
01306             for(node= sce->nodetree->nodes.first; node; node= node->next)
01307                 if(node->type==CMP_NODE_MOVIEDISTORTION)
01308                     oldnewmap_insert(fd->movieclipmap, node->storage, node->storage, 0);
01309         }
01310     }
01311 }
01312 
01313 /* set old main movie clips caches to zero if it has been restored */
01314 /* this works because freeing old main only happens after this call */
01315 void blo_end_movieclip_pointer_map(FileData *fd, Main *oldmain)
01316 {
01317     OldNew *entry= fd->movieclipmap->entries;
01318     MovieClip *clip= oldmain->movieclip.first;
01319     Scene *sce= oldmain->scene.first;
01320     int i;
01321 
01322     /* used entries were restored, so we put them to zero */
01323     for (i=0; i<fd->movieclipmap->nentries; i++, entry++) {
01324         if (entry->nr>0)
01325                 entry->newp= NULL;
01326     }
01327 
01328     for(;clip; clip= clip->id.next) {
01329         clip->cache= newmclipadr(fd, clip->cache);
01330         clip->tracking.camera.intrinsics= newmclipadr(fd, clip->tracking.camera.intrinsics);
01331     }
01332 
01333     for(; sce; sce= sce->id.next) {
01334         if(sce->nodetree) {
01335             bNode *node;
01336             for(node= sce->nodetree->nodes.first; node; node= node->next)
01337                 if(node->type==CMP_NODE_MOVIEDISTORTION)
01338                     node->storage= newmclipadr(fd, node->storage);
01339         }
01340     }
01341 }
01342 
01343 
01344 /* undo file support: add all library pointers in lookup */
01345 void blo_add_library_pointer_map(ListBase *mainlist, FileData *fd)
01346 {
01347     Main *ptr= mainlist->first;
01348     ListBase *lbarray[MAX_LIBARRAY];
01349     
01350     for(ptr= ptr->next; ptr; ptr= ptr->next) {
01351         int i= set_listbasepointers(ptr, lbarray);
01352         while(i--) {
01353             ID *id;
01354             for(id= lbarray[i]->first; id; id= id->next)
01355                 oldnewmap_insert(fd->libmap, id, id, GS(id->name));
01356         }
01357     }
01358 }
01359         
01360 
01361 /* ********** END OLD POINTERS ****************** */
01362 /* ********** READ FILE ****************** */
01363 
01364 static void switch_endian_structs(struct SDNA *filesdna, BHead *bhead)
01365 {
01366     int blocksize, nblocks;
01367     char *data;
01368 
01369     data= (char *)(bhead+1);
01370     blocksize= filesdna->typelens[ filesdna->structs[bhead->SDNAnr][0] ];
01371 
01372     nblocks= bhead->nr;
01373     while(nblocks--) {
01374         DNA_struct_switch_endian(filesdna, bhead->SDNAnr, data);
01375 
01376         data+= blocksize;
01377     }
01378 }
01379 
01380 static void *read_struct(FileData *fd, BHead *bh, const char *blockname)
01381 {
01382     void *temp= NULL;
01383 
01384     if (bh->len) {
01385         /* switch is based on file dna */
01386         if (bh->SDNAnr && (fd->flags & FD_FLAGS_SWITCH_ENDIAN))
01387             switch_endian_structs(fd->filesdna, bh);
01388 
01389         if (fd->compflags[bh->SDNAnr]) {    /* flag==0: doesn't exist anymore */
01390             if(fd->compflags[bh->SDNAnr]==2) {
01391                 temp= DNA_struct_reconstruct(fd->memsdna, fd->filesdna, fd->compflags, bh->SDNAnr, bh->nr, (bh+1));
01392             } else {
01393                 temp= MEM_mallocN(bh->len, blockname);
01394                 memcpy(temp, (bh+1), bh->len);
01395             }
01396         }
01397     }
01398 
01399     return temp;
01400 }
01401 
01402 static void link_list(FileData *fd, ListBase *lb)       /* only direct data */
01403 {
01404     Link *ln, *prev;
01405 
01406     if(lb->first==NULL) return;
01407 
01408     lb->first= newdataadr(fd, lb->first);
01409     ln= lb->first;
01410     prev= NULL;
01411     while(ln) {
01412         ln->next= newdataadr(fd, ln->next);
01413         ln->prev= prev;
01414         prev= ln;
01415         ln= ln->next;
01416     }
01417     lb->last= prev;
01418 }
01419 
01420 static void link_glob_list(FileData *fd, ListBase *lb)      /* for glob data */
01421 {
01422     Link *ln, *prev;
01423     void *poin;
01424 
01425     if(lb->first==NULL) return;
01426     poin= newdataadr(fd, lb->first);
01427     if(lb->first) {
01428         oldnewmap_insert(fd->globmap, lb->first, poin, 0);
01429     }
01430     lb->first= poin;
01431 
01432     ln= lb->first;
01433     prev= NULL;
01434     while(ln) {
01435         poin= newdataadr(fd, ln->next);
01436         if(ln->next) {
01437             oldnewmap_insert(fd->globmap, ln->next, poin, 0);
01438         }
01439         ln->next= poin;
01440         ln->prev= prev;
01441         prev= ln;
01442         ln= ln->next;
01443     }
01444     lb->last= prev;
01445 }
01446 
01447 static void test_pointer_array(FileData *fd, void **mat)
01448 {
01449 #if defined(WIN32) && !defined(FREE_WINDOWS)
01450     __int64 *lpoin, *lmat;
01451 #else
01452     long long *lpoin, *lmat;
01453 #endif
01454     int *ipoin, *imat;
01455     size_t len;
01456 
01457         /* manually convert the pointer array in
01458          * the old dna format to a pointer array in
01459          * the new dna format.
01460          */
01461     if(*mat) {
01462         len= MEM_allocN_len(*mat)/fd->filesdna->pointerlen;
01463 
01464         if(fd->filesdna->pointerlen==8 && fd->memsdna->pointerlen==4) {
01465             ipoin=imat= MEM_mallocN( len*4, "newmatar");
01466             lpoin= *mat;
01467 
01468             while(len-- > 0) {
01469                 if((fd->flags & FD_FLAGS_SWITCH_ENDIAN))
01470                     SWITCH_LONGINT(*lpoin);
01471                 *ipoin= (int) ((*lpoin) >> 3);
01472                 ipoin++;
01473                 lpoin++;
01474             }
01475             MEM_freeN(*mat);
01476             *mat= imat;
01477         }
01478 
01479         if(fd->filesdna->pointerlen==4 && fd->memsdna->pointerlen==8) {
01480             lpoin=lmat= MEM_mallocN( len*8, "newmatar");
01481             ipoin= *mat;
01482 
01483             while(len-- > 0) {
01484                 *lpoin= *ipoin;
01485                 ipoin++;
01486                 lpoin++;
01487             }
01488             MEM_freeN(*mat);
01489             *mat= lmat;
01490         }
01491     }
01492 }
01493 
01494 /* ************ READ ID Properties *************** */
01495 
01496 static void IDP_DirectLinkProperty(IDProperty *prop, int switch_endian, FileData *fd);
01497 static void IDP_LibLinkProperty(IDProperty *prop, int switch_endian, FileData *fd);
01498 
01499 static void IDP_DirectLinkIDPArray(IDProperty *prop, int switch_endian, FileData *fd)
01500 {
01501     IDProperty *array;
01502     int i;
01503 
01504     /*since we didn't save the extra buffer, set totallen to len.*/
01505     prop->totallen = prop->len;
01506     prop->data.pointer = newdataadr(fd, prop->data.pointer);
01507 
01508     array= (IDProperty*) prop->data.pointer;
01509     
01510     /* note!, idp-arrays didn't exist in 2.4x, so the pointer will be cleared
01511      * theres not really anything we can do to correct this, at least dont crash */
01512     if(array==NULL) {
01513         prop->len= 0;
01514         prop->totallen= 0;
01515     }
01516     
01517 
01518     for(i=0; i<prop->len; i++)
01519         IDP_DirectLinkProperty(&array[i], switch_endian, fd);
01520 }
01521 
01522 static void IDP_DirectLinkArray(IDProperty *prop, int switch_endian, FileData *fd)
01523 {
01524     IDProperty **array;
01525     int i;
01526 
01527     /*since we didn't save the extra buffer, set totallen to len.*/
01528     prop->totallen = prop->len;
01529     prop->data.pointer = newdataadr(fd, prop->data.pointer);
01530 
01531     if(prop->subtype == IDP_GROUP) {
01532         test_pointer_array(fd, prop->data.pointer);
01533         array= prop->data.pointer;
01534 
01535         for(i=0; i<prop->len; i++)
01536             IDP_DirectLinkProperty(array[i], switch_endian, fd);
01537     }
01538     else if(prop->subtype == IDP_DOUBLE) {
01539         if (switch_endian) {
01540             for (i=0; i<prop->len; i++) {
01541                 SWITCH_LONGINT(((double*)prop->data.pointer)[i]);
01542             }
01543         }
01544     }
01545     else {
01546         if (switch_endian) {
01547             for (i=0; i<prop->len; i++) {
01548                 SWITCH_INT(((int*)prop->data.pointer)[i]);
01549             }
01550         }
01551     }
01552 }
01553 
01554 static void IDP_DirectLinkString(IDProperty *prop, FileData *fd)
01555 {
01556     /*since we didn't save the extra string buffer, set totallen to len.*/
01557     prop->totallen = prop->len;
01558     prop->data.pointer = newdataadr(fd, prop->data.pointer);
01559 }
01560 
01561 static void IDP_DirectLinkGroup(IDProperty *prop, int switch_endian, FileData *fd)
01562 {
01563     ListBase *lb = &prop->data.group;
01564     IDProperty *loop;
01565 
01566     link_list(fd, lb);
01567 
01568     /*Link child id properties now*/
01569     for (loop=prop->data.group.first; loop; loop=loop->next) {
01570         IDP_DirectLinkProperty(loop, switch_endian, fd);
01571     }
01572 }
01573 
01574 static void IDP_DirectLinkProperty(IDProperty *prop, int switch_endian, FileData *fd)
01575 {
01576     switch (prop->type) {
01577         case IDP_GROUP:
01578             IDP_DirectLinkGroup(prop, switch_endian, fd);
01579             break;
01580         case IDP_STRING:
01581             IDP_DirectLinkString(prop, fd);
01582             break;
01583         case IDP_ARRAY:
01584             IDP_DirectLinkArray(prop, switch_endian, fd);
01585             break;
01586         case IDP_IDPARRAY:
01587             IDP_DirectLinkIDPArray(prop, switch_endian, fd);
01588             break;
01589         case IDP_DOUBLE:
01590             /* erg, stupid doubles.  since I'm storing them
01591              * in the same field as int val; val2 in the
01592              * IDPropertyData struct, they have to deal with
01593              * endianness specifically
01594 
01595              * in theory, val and val2 would've already been swapped
01596              * if switch_endian is true, so we have to first unswap
01597              * them then reswap them as a single 64-bit entity.
01598              */
01599             
01600             if (switch_endian) {
01601                 SWITCH_INT(prop->data.val);
01602                 SWITCH_INT(prop->data.val2);
01603                 SWITCH_LONGINT(prop->data.val);
01604             }
01605             
01606             break;
01607     }
01608 }
01609 
01610 /*stub function*/
01611 static void IDP_LibLinkProperty(IDProperty *UNUSED(prop), int UNUSED(switch_endian), FileData *UNUSED(fd))
01612 {
01613 }
01614 
01615 /* ************ READ CurveMapping *************** */
01616 
01617 /* cuma itself has been read! */
01618 static void direct_link_curvemapping(FileData *fd, CurveMapping *cumap)
01619 {
01620     int a;
01621     
01622     /* flag seems to be able to hang? Maybe old files... not bad to clear anyway */
01623     cumap->flag &= ~CUMA_PREMULLED;
01624     
01625     for(a=0; a<CM_TOT; a++) {
01626         cumap->cm[a].curve= newdataadr(fd, cumap->cm[a].curve);
01627         cumap->cm[a].table= NULL;
01628         cumap->cm[a].premultable= NULL;
01629     }
01630 }
01631 
01632 /* ************ READ Brush *************** */
01633 /* library brush linking after fileread */
01634 static void lib_link_brush(FileData *fd, Main *main)
01635 {
01636     Brush *brush;
01637     
01638     /* only link ID pointers */
01639     for(brush= main->brush.first; brush; brush= brush->id.next) {
01640         if(brush->id.flag & LIB_NEEDLINK) {
01641             brush->id.flag -= LIB_NEEDLINK;
01642 
01643             brush->mtex.tex= newlibadr_us(fd, brush->id.lib, brush->mtex.tex);
01644             brush->clone.image= newlibadr_us(fd, brush->id.lib, brush->clone.image);
01645         }
01646     }
01647 }
01648 
01649 static void direct_link_brush(FileData *fd, Brush *brush)
01650 {
01651     /* brush itself has been read */
01652 
01653     /* fallof curve */
01654     brush->curve= newdataadr(fd, brush->curve);
01655     if(brush->curve)
01656         direct_link_curvemapping(fd, brush->curve);
01657     else
01658         brush_curve_preset(brush, CURVE_PRESET_SHARP);
01659 
01660     brush->preview= NULL;
01661     brush->icon_imbuf= NULL;
01662 }
01663 
01664 static void direct_link_script(FileData *UNUSED(fd), Script *script)
01665 {
01666     script->id.us = 1;
01667     SCRIPT_SET_NULL(script)
01668 }
01669 
01670 
01671 /* ************ READ PACKEDFILE *************** */
01672 
01673 static PackedFile *direct_link_packedfile(FileData *fd, PackedFile *oldpf)
01674 {
01675     PackedFile *pf= newdataadr(fd, oldpf);
01676 
01677     if (pf) {
01678         pf->data= newdataadr(fd, pf->data);
01679     }
01680 
01681     return pf;
01682 }
01683 
01684 /* ************ READ IMAGE PREVIEW *************** */
01685 
01686 static PreviewImage *direct_link_preview_image(FileData *fd, PreviewImage *old_prv)
01687 {
01688     PreviewImage *prv= newdataadr(fd, old_prv);
01689 
01690     if (prv) {
01691         int i;
01692         for (i=0; i < NUM_ICON_SIZES; ++i) {
01693             if (prv->rect[i]) {
01694                 prv->rect[i] = newdataadr(fd, prv->rect[i]);
01695             }
01696         }
01697     }
01698 
01699     return prv;
01700 }
01701 
01702 /* ************ READ ANIMATION STUFF ***************** */
01703 
01704 /* Legacy Data Support (for Version Patching) ----------------------------- */
01705 
01706 // XXX depreceated - old animation system
01707 static void lib_link_ipo(FileData *fd, Main *main)
01708 {
01709     Ipo *ipo;
01710 
01711     ipo= main->ipo.first;
01712     while(ipo) {
01713         if(ipo->id.flag & LIB_NEEDLINK) {
01714             IpoCurve *icu;
01715             for(icu= ipo->curve.first; icu; icu= icu->next) {
01716                 if(icu->driver)
01717                     icu->driver->ob= newlibadr(fd, ipo->id.lib, icu->driver->ob);
01718             }
01719             ipo->id.flag -= LIB_NEEDLINK;
01720         }
01721         ipo= ipo->id.next;
01722     }
01723 }
01724 
01725 // XXX depreceated - old animation system
01726 static void direct_link_ipo(FileData *fd, Ipo *ipo)
01727 {
01728     IpoCurve *icu;
01729 
01730     link_list(fd, &(ipo->curve));
01731     icu= ipo->curve.first;
01732     while(icu) {
01733         icu->bezt= newdataadr(fd, icu->bezt);
01734         icu->bp= newdataadr(fd, icu->bp);
01735         icu->driver= newdataadr(fd, icu->driver);
01736         icu= icu->next;
01737     }
01738 }
01739 
01740 // XXX depreceated - old animation system
01741 static void lib_link_nlastrips(FileData *fd, ID *id, ListBase *striplist)
01742 {
01743     bActionStrip *strip;
01744     bActionModifier *amod;
01745     
01746     for (strip=striplist->first; strip; strip=strip->next){
01747         strip->object = newlibadr(fd, id->lib, strip->object);
01748         strip->act = newlibadr_us(fd, id->lib, strip->act);
01749         strip->ipo = newlibadr(fd, id->lib, strip->ipo);
01750         for(amod= strip->modifiers.first; amod; amod= amod->next)
01751             amod->ob= newlibadr(fd, id->lib, amod->ob);
01752     }
01753 }
01754 
01755 // XXX depreceated - old animation system
01756 static void direct_link_nlastrips(FileData *fd, ListBase *strips)
01757 {
01758     bActionStrip *strip;
01759     
01760     link_list(fd, strips);
01761     
01762     for(strip= strips->first; strip; strip= strip->next)
01763         link_list(fd, &strip->modifiers);
01764 }
01765 
01766 // XXX depreceated - old animation system
01767 static void lib_link_constraint_channels(FileData *fd, ID *id, ListBase *chanbase)
01768 {
01769     bConstraintChannel *chan;
01770 
01771     for (chan=chanbase->first; chan; chan=chan->next){
01772         chan->ipo = newlibadr_us(fd, id->lib, chan->ipo);
01773     }
01774 }
01775 
01776 /* Data Linking ----------------------------- */
01777 
01778 static void lib_link_fmodifiers(FileData *fd, ID *id, ListBase *list)
01779 {
01780     FModifier *fcm;
01781     
01782     for (fcm= list->first; fcm; fcm= fcm->next) {
01783         /* data for specific modifiers */
01784         switch (fcm->type) {
01785             case FMODIFIER_TYPE_PYTHON:
01786             {
01787                 FMod_Python *data= (FMod_Python *)fcm->data;
01788                 data->script = newlibadr(fd, id->lib, data->script);
01789             }
01790                 break;
01791         }
01792     }
01793 }
01794 
01795 static void lib_link_fcurves(FileData *fd, ID *id, ListBase *list) 
01796 {
01797     FCurve *fcu;
01798     
01799     if (list == NULL)
01800         return;
01801     
01802     /* relink ID-block references... */
01803     for (fcu= list->first; fcu; fcu= fcu->next) {
01804         /* driver data */
01805         if (fcu->driver) {
01806             ChannelDriver *driver= fcu->driver;
01807             DriverVar *dvar;
01808             
01809             for (dvar= driver->variables.first; dvar; dvar= dvar->next) {
01810                 DRIVER_TARGETS_LOOPER(dvar)
01811                 {   
01812                     /* only relink if still used */
01813                     if (tarIndex < dvar->num_targets)
01814                         dtar->id= newlibadr(fd, id->lib, dtar->id); 
01815                     else
01816                         dtar->id= NULL;
01817                 }
01818                 DRIVER_TARGETS_LOOPER_END
01819             }
01820         }
01821         
01822         /* modifiers */
01823         lib_link_fmodifiers(fd, id, &fcu->modifiers);
01824     }
01825 }
01826 
01827 
01828 /* NOTE: this assumes that link_list has already been called on the list */
01829 static void direct_link_fmodifiers(FileData *fd, ListBase *list)
01830 {
01831     FModifier *fcm;
01832     
01833     for (fcm= list->first; fcm; fcm= fcm->next) {
01834         /* relink general data */
01835         fcm->data = newdataadr(fd, fcm->data);
01836         fcm->edata= NULL;
01837         
01838         /* do relinking of data for specific types */
01839         switch (fcm->type) {
01840             case FMODIFIER_TYPE_GENERATOR:
01841             {
01842                 FMod_Generator *data= (FMod_Generator *)fcm->data;
01843                 
01844                 data->coefficients= newdataadr(fd, data->coefficients);
01845 
01846                 if(fd->flags & FD_FLAGS_SWITCH_ENDIAN) {
01847                     unsigned int a;
01848                     for(a = 0; a < data->arraysize; a++)
01849                         SWITCH_INT(data->coefficients[a]);
01850                 }
01851             }
01852                 break;
01853             case FMODIFIER_TYPE_ENVELOPE:
01854             {
01855                 FMod_Envelope *data= (FMod_Envelope *)fcm->data;
01856                 
01857                 data->data= newdataadr(fd, data->data);
01858             }
01859                 break;
01860             case FMODIFIER_TYPE_PYTHON:
01861             {
01862                 FMod_Python *data= (FMod_Python *)fcm->data;
01863                 
01864                 data->prop = newdataadr(fd, data->prop);
01865                 IDP_DirectLinkProperty(data->prop, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
01866             }
01867                 break;
01868         }
01869     }
01870 }
01871 
01872 /* NOTE: this assumes that link_list has already been called on the list */
01873 static void direct_link_fcurves(FileData *fd, ListBase *list)
01874 {
01875     FCurve *fcu;
01876     
01877     /* link F-Curve data to F-Curve again (non ID-libs) */
01878     for (fcu= list->first; fcu; fcu= fcu->next) {
01879         /* curve data */
01880         fcu->bezt= newdataadr(fd, fcu->bezt);
01881         fcu->fpt= newdataadr(fd, fcu->fpt);
01882         
01883         /* rna path */
01884         fcu->rna_path= newdataadr(fd, fcu->rna_path);
01885         
01886         /* group */
01887         fcu->grp= newdataadr(fd, fcu->grp);
01888         
01889         /* driver */
01890         fcu->driver= newdataadr(fd, fcu->driver);
01891         if (fcu->driver) {
01892             ChannelDriver *driver= fcu->driver;
01893             DriverVar *dvar;
01894 
01895             driver->expr_comp= NULL;
01896             
01897             /* relink variables, targets and their paths */
01898             link_list(fd, &driver->variables);
01899             for (dvar= driver->variables.first; dvar; dvar= dvar->next) {
01900                 DRIVER_TARGETS_LOOPER(dvar)
01901                 {
01902                     /* only relink the targets being used */
01903                     if (tarIndex < dvar->num_targets)
01904                         dtar->rna_path= newdataadr(fd, dtar->rna_path);
01905                     else
01906                         dtar->rna_path= NULL;
01907                 }
01908                 DRIVER_TARGETS_LOOPER_END
01909             }
01910         }
01911         
01912         /* modifiers */
01913         link_list(fd, &fcu->modifiers);
01914         direct_link_fmodifiers(fd, &fcu->modifiers);
01915     }
01916 }
01917 
01918 
01919 static void lib_link_action(FileData *fd, Main *main)
01920 {
01921     bAction *act;
01922     bActionChannel *chan;
01923 
01924     for (act= main->action.first; act; act= act->id.next) {
01925         if (act->id.flag & LIB_NEEDLINK) {
01926             act->id.flag -= LIB_NEEDLINK;
01927             
01928 // XXX depreceated - old animation system <<<
01929             for (chan=act->chanbase.first; chan; chan=chan->next) {
01930                 chan->ipo= newlibadr_us(fd, act->id.lib, chan->ipo);
01931                 lib_link_constraint_channels(fd, &act->id, &chan->constraintChannels);
01932             }
01933 // >>> XXX depreceated - old animation system
01934             
01935             lib_link_fcurves(fd, &act->id, &act->curves);
01936         }
01937     }
01938 }
01939 
01940 static void direct_link_action(FileData *fd, bAction *act)
01941 {
01942     bActionChannel *achan; // XXX depreceated - old animation system
01943     bActionGroup *agrp;
01944 
01945     link_list(fd, &act->curves);
01946     link_list(fd, &act->chanbase); // XXX depreceated - old animation system
01947     link_list(fd, &act->groups);
01948     link_list(fd, &act->markers);
01949 
01950 // XXX depreceated - old animation system <<<
01951     for (achan = act->chanbase.first; achan; achan=achan->next) {
01952         achan->grp= newdataadr(fd, achan->grp);
01953         
01954         link_list(fd, &achan->constraintChannels);
01955     }
01956 // >>> XXX depreceated - old animation system
01957 
01958     direct_link_fcurves(fd, &act->curves);
01959     
01960     for (agrp = act->groups.first; agrp; agrp= agrp->next) {
01961         agrp->channels.first= newdataadr(fd, agrp->channels.first);
01962         agrp->channels.last= newdataadr(fd, agrp->channels.last);
01963     }
01964 }
01965 
01966 static void lib_link_nladata_strips(FileData *fd, ID *id, ListBase *list)
01967 {
01968     NlaStrip *strip;
01969     
01970     for (strip= list->first; strip; strip= strip->next) {
01971         /* check strip's children */
01972         lib_link_nladata_strips(fd, id, &strip->strips);
01973         
01974         /* check strip's F-Curves */
01975         lib_link_fcurves(fd, id, &strip->fcurves);
01976         
01977         /* reassign the counted-reference to action */
01978         strip->act = newlibadr_us(fd, id->lib, strip->act);
01979         
01980         /* fix action id-root (i.e. if it comes from a pre 2.57 .blend file) */
01981         if ((strip->act) && (strip->act->idroot == 0))
01982             strip->act->idroot = GS(id->name);
01983     }
01984 }
01985 
01986 static void lib_link_nladata(FileData *fd, ID *id, ListBase *list)
01987 {
01988     NlaTrack *nlt;
01989     
01990     /* we only care about the NLA strips inside the tracks */
01991     for (nlt= list->first; nlt; nlt= nlt->next) {
01992         lib_link_nladata_strips(fd, id, &nlt->strips);
01993     }
01994 }
01995 
01996 /* This handles Animato NLA-Strips linking 
01997  * NOTE: this assumes that link_list has already been called on the list 
01998  */
01999 static void direct_link_nladata_strips(FileData *fd, ListBase *list)
02000 {
02001     NlaStrip *strip;
02002     
02003     for (strip= list->first; strip; strip= strip->next) {
02004         /* strip's child strips */
02005         link_list(fd, &strip->strips);
02006         direct_link_nladata_strips(fd, &strip->strips);
02007         
02008         /* strip's F-Curves */
02009         link_list(fd, &strip->fcurves);
02010         direct_link_fcurves(fd, &strip->fcurves);
02011         
02012         /* strip's F-Modifiers */
02013         link_list(fd, &strip->modifiers);
02014         direct_link_fmodifiers(fd, &strip->modifiers);
02015     }
02016 }
02017 
02018 /* NOTE: this assumes that link_list has already been called on the list */
02019 static void direct_link_nladata(FileData *fd, ListBase *list)
02020 {
02021     NlaTrack *nlt;
02022     
02023     for (nlt= list->first; nlt; nlt= nlt->next) {
02024         /* relink list of strips */
02025         link_list(fd, &nlt->strips);
02026         
02027         /* relink strip data */
02028         direct_link_nladata_strips(fd, &nlt->strips);
02029     }
02030 }
02031 
02032 /* ------- */
02033 
02034 static void lib_link_keyingsets(FileData *fd, ID *id, ListBase *list)
02035 {
02036     KeyingSet *ks;
02037     KS_Path *ksp;
02038     
02039     /* here, we're only interested in the ID pointer stored in some of the paths */
02040     for (ks= list->first; ks; ks= ks->next) {
02041         for (ksp= ks->paths.first; ksp; ksp= ksp->next) {
02042             ksp->id= newlibadr(fd, id->lib, ksp->id); 
02043         }
02044     }
02045 }
02046 
02047 /* NOTE: this assumes that link_list has already been called on the list */
02048 static void direct_link_keyingsets(FileData *fd, ListBase *list)
02049 {
02050     KeyingSet *ks;
02051     KS_Path *ksp;
02052     
02053     /* link KeyingSet data to KeyingSet again (non ID-libs) */
02054     for (ks= list->first; ks; ks= ks->next) {
02055         /* paths */
02056         link_list(fd, &ks->paths);
02057         
02058         for (ksp= ks->paths.first; ksp; ksp= ksp->next) {
02059             /* rna path */
02060             ksp->rna_path= newdataadr(fd, ksp->rna_path);
02061         }
02062     }
02063 }
02064 
02065 /* ------- */
02066 
02067 static void lib_link_animdata(FileData *fd, ID *id, AnimData *adt)
02068 {
02069     if (adt == NULL)
02070         return;
02071     
02072     /* link action data */
02073     adt->action= newlibadr_us(fd, id->lib, adt->action);
02074     adt->tmpact= newlibadr_us(fd, id->lib, adt->tmpact);
02075     
02076     /* fix action id-roots (i.e. if they come from a pre 2.57 .blend file) */
02077     if ((adt->action) && (adt->action->idroot == 0))
02078         adt->action->idroot = GS(id->name);
02079     if ((adt->tmpact) && (adt->tmpact->idroot == 0))
02080         adt->tmpact->idroot = GS(id->name);
02081     
02082     /* link drivers */
02083     lib_link_fcurves(fd, id, &adt->drivers);
02084     
02085     /* overrides don't have lib-link for now, so no need to do anything */
02086     
02087     /* link NLA-data */
02088     lib_link_nladata(fd, id, &adt->nla_tracks);
02089 }
02090 
02091 static void direct_link_animdata(FileData *fd, AnimData *adt)
02092 {
02093     /* NOTE: must have called newdataadr already before doing this... */
02094     if (adt == NULL)
02095         return;
02096     
02097     /* link drivers */
02098     link_list(fd, &adt->drivers);
02099     direct_link_fcurves(fd, &adt->drivers);
02100     
02101     /* link overrides */
02102     // TODO...
02103     
02104     /* link NLA-data */
02105     link_list(fd, &adt->nla_tracks);
02106     direct_link_nladata(fd, &adt->nla_tracks);
02107     
02108     /* relink active strip - even though strictly speaking this should only be used
02109      * if we're in 'tweaking mode', we need to be able to have this loaded back for
02110      * undo, but also since users may not exit tweakmode before saving (#24535)
02111      */
02112     // TODO: it's not really nice that anyone should be able to save the file in this
02113     //      state, but it's going to be too hard to enforce this single case...
02114     adt->actstrip= newdataadr(fd, adt->actstrip);
02115 }   
02116 
02117 /* ************ READ MOTION PATHS *************** */
02118 
02119 /* direct data for cache */
02120 static void direct_link_motionpath(FileData *fd, bMotionPath *mpath)
02121 {
02122     /* sanity check */
02123     if (mpath == NULL)
02124         return;
02125     
02126     /* relink points cache */
02127     mpath->points= newdataadr(fd, mpath->points);
02128 }
02129 
02130 /* ************ READ NODE TREE *************** */
02131 
02132 /* singe node tree (also used for material/scene trees), ntree is not NULL */
02133 static void lib_link_ntree(FileData *fd, ID *id, bNodeTree *ntree)
02134 {
02135     bNode *node;
02136     
02137     if(ntree->adt) lib_link_animdata(fd, &ntree->id, ntree->adt);
02138     
02139     ntree->gpd= newlibadr_us(fd, id->lib, ntree->gpd);
02140     
02141     for(node= ntree->nodes.first; node; node= node->next)
02142         node->id= newlibadr_us(fd, id->lib, node->id);
02143 }
02144 
02145 /* library ntree linking after fileread */
02146 static void lib_link_nodetree(FileData *fd, Main *main)
02147 {
02148     bNodeTree *ntree;
02149     
02150     /* only link ID pointers */
02151     for(ntree= main->nodetree.first; ntree; ntree= ntree->id.next) {
02152         if(ntree->id.flag & LIB_NEEDLINK) {
02153             ntree->id.flag -= LIB_NEEDLINK;
02154             lib_link_ntree(fd, &ntree->id, ntree);
02155         }
02156     }
02157 }
02158 
02159 static void do_versions_socket_default_value(bNodeSocket *sock)
02160 {
02161     bNodeSocketValueFloat *valfloat;
02162     bNodeSocketValueVector *valvector;
02163     bNodeSocketValueRGBA *valrgba;
02164     
02165     if (sock->default_value)
02166         return;
02167     
02168     switch (sock->type) {
02169     case SOCK_FLOAT:
02170         valfloat = sock->default_value = MEM_callocN(sizeof(bNodeSocketValueFloat), "default socket value");
02171         valfloat->value = sock->ns.vec[0];
02172         valfloat->min = sock->ns.min;
02173         valfloat->max = sock->ns.max;
02174         valfloat->subtype = PROP_NONE;
02175         break;
02176     case SOCK_VECTOR:
02177         valvector = sock->default_value = MEM_callocN(sizeof(bNodeSocketValueVector), "default socket value");
02178         copy_v3_v3(valvector->value, sock->ns.vec);
02179         valvector->min = sock->ns.min;
02180         valvector->max = sock->ns.max;
02181         valvector->subtype = PROP_NONE;
02182         break;
02183     case SOCK_RGBA:
02184         valrgba = sock->default_value = MEM_callocN(sizeof(bNodeSocketValueRGBA), "default socket value");
02185         copy_v4_v4(valrgba->value, sock->ns.vec);
02186         break;
02187     }
02188 }
02189 
02190 static void do_versions_nodetree_default_value(bNodeTree *ntree)
02191 {
02192     bNode *node;
02193     bNodeSocket *sock;
02194     for (node=ntree->nodes.first; node; node=node->next) {
02195         for (sock=node->inputs.first; sock; sock=sock->next)
02196             do_versions_socket_default_value(sock);
02197         for (sock=node->outputs.first; sock; sock=sock->next)
02198             do_versions_socket_default_value(sock);
02199     }
02200     for (sock=ntree->inputs.first; sock; sock=sock->next)
02201         do_versions_socket_default_value(sock);
02202     for (sock=ntree->outputs.first; sock; sock=sock->next)
02203         do_versions_socket_default_value(sock);
02204 }
02205 
02206 static void lib_nodetree_init_types_cb(void *UNUSED(data), ID *UNUSED(id), bNodeTree *ntree)
02207 {
02208     bNode *node;
02209     
02210     ntreeInitTypes(ntree);
02211 
02212     /* need to do this here instead of in do_versions, otherwise next function can crash */
02213     do_versions_nodetree_default_value(ntree);
02214     
02215     /* XXX could be replaced by do_versions for new nodes */
02216     for (node=ntree->nodes.first; node; node=node->next)
02217         node_verify_socket_templates(ntree, node);
02218 }
02219 
02220 /* updates group node socket own_index so that
02221  * external links to/from the group node are preserved.
02222  */
02223 static void lib_node_do_versions_group_indices(bNode *gnode)
02224 {
02225     bNodeTree *ngroup= (bNodeTree*)gnode->id;
02226     bNode *intnode;
02227     bNodeSocket *sock, *gsock, *intsock;
02228     int found;
02229     
02230     for (sock=gnode->outputs.first; sock; sock=sock->next) {
02231         int old_index = sock->to_index;
02232         for (gsock=ngroup->outputs.first; gsock; gsock=gsock->next) {
02233             if (gsock->link && gsock->link->fromsock->own_index == old_index) {
02234                 sock->own_index = gsock->own_index;
02235                 break;
02236             }
02237         }
02238     }
02239     for (sock=gnode->inputs.first; sock; sock=sock->next) {
02240         int old_index = sock->to_index;
02241         /* can't use break in double loop */
02242         found = 0;
02243         for (intnode=ngroup->nodes.first; intnode && !found; intnode=intnode->next) {
02244             for (intsock=intnode->inputs.first; intsock; intsock=intsock->next) {
02245                 if (intsock->own_index == old_index && intsock->link) {
02246                     sock->own_index = intsock->link->fromsock->own_index;
02247                     found = 1;
02248                     break;
02249                 }
02250             }
02251         }
02252     }
02253 }
02254 
02255 /* updates external links for all group nodes in a tree */
02256 static void lib_nodetree_do_versions_group_indices_cb(void *UNUSED(data), ID *UNUSED(id), bNodeTree *ntree)
02257 {
02258     bNode *node;
02259     
02260     for (node=ntree->nodes.first; node; node=node->next) {
02261         if (node->type==NODE_GROUP) {
02262             bNodeTree *ngroup= (bNodeTree*)node->id;
02263             if (ngroup && (ngroup->flag & NTREE_DO_VERSIONS_GROUP_EXPOSE))
02264                 lib_node_do_versions_group_indices(node);
02265         }
02266     }
02267 }
02268 
02269 /* make an update call for the tree */
02270 static void lib_nodetree_do_versions_update_cb(void *UNUSED(data), ID *UNUSED(id), bNodeTree *ntree)
02271 {
02272     if (ntree->update)
02273         ntreeUpdateTree(ntree);
02274 }
02275 
02276 /* verify types for nodes and groups, all data has to be read */
02277 /* open = 0: appending/linking, open = 1: open new file (need to clean out dynamic
02278 * typedefs*/
02279 static void lib_verify_nodetree(Main *main, int UNUSED(open))
02280 {
02281     bNodeTree *ntree;
02282     int i;
02283     bNodeTreeType *ntreetype;
02284 
02285     /* this crashes blender on undo/redo
02286         if(open==1) {
02287             reinit_nodesystem();
02288         }*/
02289     
02290     /* set node->typeinfo pointers */
02291     for (i=0; i < NUM_NTREE_TYPES; ++i) {
02292         ntreetype= ntreeGetType(i);
02293         if (ntreetype && ntreetype->foreach_nodetree)
02294             ntreetype->foreach_nodetree(main, NULL, lib_nodetree_init_types_cb);
02295     }
02296     for(ntree= main->nodetree.first; ntree; ntree= ntree->id.next)
02297         lib_nodetree_init_types_cb(NULL, NULL, ntree);
02298     
02299     {
02300         int has_old_groups=0;
02301         /* XXX this should actually be part of do_versions, but since we need
02302          * finished library linking, it is not possible there. Instead in do_versions
02303          * we have set the NTREE_DO_VERSIONS flag, so at this point we can do the
02304          * actual group node updates.
02305          */
02306         for(ntree= main->nodetree.first; ntree; ntree= ntree->id.next) {
02307             if (ntree->flag & NTREE_DO_VERSIONS_GROUP_EXPOSE) {
02308                 /* this adds copies and links from all unlinked internal sockets to group inputs/outputs. */
02309                 node_group_expose_all_sockets(ntree);
02310                 has_old_groups = 1;
02311             }
02312         }
02313         
02314         if (has_old_groups) {
02315             for (i=0; i < NUM_NTREE_TYPES; ++i) {
02316                 ntreetype= ntreeGetType(i);
02317                 if (ntreetype && ntreetype->foreach_nodetree)
02318                     ntreetype->foreach_nodetree(main, NULL, lib_nodetree_do_versions_group_indices_cb);
02319             }
02320         }
02321         
02322         for(ntree= main->nodetree.first; ntree; ntree= ntree->id.next)
02323             ntree->flag &= ~NTREE_DO_VERSIONS_GROUP_EXPOSE;
02324     }
02325     
02326     /* verify all group user nodes */
02327     for(ntree= main->nodetree.first; ntree; ntree= ntree->id.next) {
02328         ntreeVerifyNodes(main, &ntree->id);
02329     }
02330     
02331     /* make update calls where necessary */
02332     {
02333         for(ntree= main->nodetree.first; ntree; ntree= ntree->id.next)
02334             if (ntree->update)
02335                 ntreeUpdateTree(ntree);
02336 
02337         for (i=0; i < NUM_NTREE_TYPES; ++i) {
02338             ntreetype= ntreeGetType(i);
02339             if (ntreetype && ntreetype->foreach_nodetree)
02340                 ntreetype->foreach_nodetree(main, NULL, lib_nodetree_do_versions_update_cb);
02341         }
02342     }
02343 }
02344 
02345 static void direct_link_node_socket(FileData *fd, bNodeSocket *sock)
02346 {
02347     sock->link= newdataadr(fd, sock->link);
02348     sock->storage= newdataadr(fd, sock->storage);
02349     sock->default_value= newdataadr(fd, sock->default_value);
02350     sock->cache= NULL;
02351 }
02352 
02353 /* ntree itself has been read! */
02354 static void direct_link_nodetree(FileData *fd, bNodeTree *ntree)
02355 {
02356     /* note: writing and reading goes in sync, for speed */
02357     bNode *node;
02358     bNodeSocket *sock;
02359     bNodeLink *link;
02360     
02361     ntree->init= 0;     /* to set callbacks and force setting types */
02362     ntree->progress= NULL;
02363     ntree->execdata= NULL;
02364     
02365     ntree->adt= newdataadr(fd, ntree->adt);
02366     direct_link_animdata(fd, ntree->adt);
02367     
02368     link_list(fd, &ntree->nodes);
02369     for(node= ntree->nodes.first; node; node= node->next) {
02370         if(node->type == NODE_DYNAMIC) {
02371             node->custom1= 0;
02372             node->custom1= BSET(node->custom1, NODE_DYNAMIC_LOADED);
02373         }
02374 
02375         node->typeinfo= NULL;
02376         
02377         link_list(fd, &node->inputs);
02378         link_list(fd, &node->outputs);
02379         
02380         if(node->type == CMP_NODE_MOVIEDISTORTION) {
02381             node->storage= newmclipadr(fd, node->storage);
02382         } else
02383             node->storage= newdataadr(fd, node->storage);
02384 
02385         if(node->storage) {
02386             /* could be handlerized at some point */
02387             if(ntree->type==NTREE_SHADER && (node->type==SH_NODE_CURVE_VEC || node->type==SH_NODE_CURVE_RGB))
02388                 direct_link_curvemapping(fd, node->storage);
02389             else if(ntree->type==NTREE_COMPOSIT) {
02390                 if( ELEM4(node->type, CMP_NODE_TIME, CMP_NODE_CURVE_VEC, CMP_NODE_CURVE_RGB, CMP_NODE_HUECORRECT))
02391                     direct_link_curvemapping(fd, node->storage);
02392                 else if(ELEM3(node->type, CMP_NODE_IMAGE, CMP_NODE_VIEWER, CMP_NODE_SPLITVIEWER))
02393                     ((ImageUser *)node->storage)->ok= 1;
02394             }
02395             else if( ntree->type==NTREE_TEXTURE) {
02396                 if(node->type==TEX_NODE_CURVE_RGB || node->type==TEX_NODE_CURVE_TIME)
02397                     direct_link_curvemapping(fd, node->storage);
02398                 else if(node->type==TEX_NODE_IMAGE)
02399                     ((ImageUser *)node->storage)->ok= 1;
02400             }
02401         }
02402     }
02403     link_list(fd, &ntree->links);
02404     
02405     /* external sockets */
02406     link_list(fd, &ntree->inputs);
02407     link_list(fd, &ntree->outputs);
02408     
02409     /* and we connect the rest */
02410     for(node= ntree->nodes.first; node; node= node->next) {
02411         node->parent = newdataadr(fd, node->parent);
02412         node->preview= newimaadr(fd, node->preview);
02413         node->lasty= 0;
02414         
02415         for(sock= node->inputs.first; sock; sock= sock->next)
02416             direct_link_node_socket(fd, sock);
02417         for(sock= node->outputs.first; sock; sock= sock->next)
02418             direct_link_node_socket(fd, sock);
02419     }
02420     for(sock= ntree->inputs.first; sock; sock= sock->next)
02421         direct_link_node_socket(fd, sock);
02422     for(sock= ntree->outputs.first; sock; sock= sock->next)
02423         direct_link_node_socket(fd, sock);
02424     
02425     for(link= ntree->links.first; link; link= link->next) {
02426         link->fromnode= newdataadr(fd, link->fromnode);
02427         link->tonode= newdataadr(fd, link->tonode);
02428         link->fromsock= newdataadr(fd, link->fromsock);
02429         link->tosock= newdataadr(fd, link->tosock);
02430     }
02431     
02432     /* type verification is in lib-link */
02433 }
02434 
02435 /* ************ READ ARMATURE ***************** */
02436 
02437 /* temp struct used to transport needed info to lib_link_constraint_cb() */
02438 typedef struct tConstraintLinkData {
02439     FileData *fd;
02440     ID *id;
02441 } tConstraintLinkData;
02442 /* callback function used to relink constraint ID-links */
02443 static void lib_link_constraint_cb(bConstraint *UNUSED(con), ID **idpoin, void *userdata)
02444 {
02445     tConstraintLinkData *cld= (tConstraintLinkData *)userdata;
02446     *idpoin = newlibadr(cld->fd, cld->id->lib, *idpoin);
02447 }
02448 
02449 static void lib_link_constraints(FileData *fd, ID *id, ListBase *conlist)
02450 {
02451     tConstraintLinkData cld;
02452     bConstraint *con;
02453     
02454     /* legacy fixes */
02455     for (con = conlist->first; con; con=con->next) {
02456         /* patch for error introduced by changing constraints (dunno how) */
02457         /* if con->data type changes, dna cannot resolve the pointer! (ton) */
02458         if(con->data==NULL) {
02459             con->type= CONSTRAINT_TYPE_NULL;
02460         }
02461         /* own ipo, all constraints have it */
02462         con->ipo= newlibadr_us(fd, id->lib, con->ipo); // XXX depreceated - old animation system
02463     }
02464     
02465     /* relink all ID-blocks used by the constraints */
02466     cld.fd= fd;
02467     cld.id= id;
02468     
02469     id_loop_constraints(conlist, lib_link_constraint_cb, &cld);
02470 }
02471 
02472 static void direct_link_constraints(FileData *fd, ListBase *lb)
02473 {
02474     bConstraint *con;
02475 
02476     link_list(fd, lb);
02477     for (con=lb->first; con; con=con->next) {
02478         con->data = newdataadr(fd, con->data);
02479         
02480         switch (con->type) {
02481             case CONSTRAINT_TYPE_PYTHON:
02482             {
02483                 bPythonConstraint *data= con->data;
02484                 
02485                 link_list(fd, &data->targets);
02486                 
02487                 data->prop = newdataadr(fd, data->prop);
02488                 if (data->prop)
02489                     IDP_DirectLinkProperty(data->prop, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
02490             }
02491                 break;
02492             case CONSTRAINT_TYPE_SPLINEIK:
02493             {
02494                 bSplineIKConstraint *data= con->data;
02495                 
02496                 data->points= newdataadr(fd, data->points);
02497             }
02498                 break;
02499             case CONSTRAINT_TYPE_KINEMATIC:
02500             {
02501                 con->lin_error = 0.f;
02502                 con->rot_error = 0.f;
02503             }
02504             case CONSTRAINT_TYPE_CHILDOF:
02505             {
02506                 /* XXX version patch, in older code this flag wasn't always set, and is inherent to type */
02507                 if(con->ownspace == CONSTRAINT_SPACE_POSE)
02508                     con->flag |= CONSTRAINT_SPACEONCE;
02509             }
02510                 break;
02511         }
02512     }
02513 }
02514 
02515 static void lib_link_pose(FileData *fd, Object *ob, bPose *pose)
02516 {
02517     bPoseChannel *pchan;
02518     bArmature *arm= ob->data;
02519     int rebuild;
02520     
02521     if (!pose || !arm)
02522         return;
02523     
02524 
02525     /* always rebuild to match proxy or lib changes */
02526     rebuild= ob->proxy || (ob->id.lib==NULL && arm->id.lib);
02527 
02528     if(ob->proxy) {
02529         /* sync proxy layer */
02530         if(pose->proxy_layer)
02531             arm->layer = pose->proxy_layer;
02532         
02533         /* sync proxy active bone */
02534         if(pose->proxy_act_bone[0]) {
02535             Bone *bone = get_named_bone(arm, pose->proxy_act_bone);
02536             if (bone)
02537                 arm->act_bone = bone;
02538         }
02539     }
02540 
02541     for (pchan = pose->chanbase.first; pchan; pchan=pchan->next) {
02542         lib_link_constraints(fd, (ID *)ob, &pchan->constraints);
02543         
02544         /* hurms... loop in a loop, but yah... later... (ton) */
02545         pchan->bone= get_named_bone(arm, pchan->name);
02546         
02547         pchan->custom= newlibadr_us(fd, arm->id.lib, pchan->custom);
02548         if(pchan->bone==NULL)
02549             rebuild= 1;
02550         else if(ob->id.lib==NULL && arm->id.lib) {
02551             /* local pose selection copied to armature, bit hackish */
02552             pchan->bone->flag &= ~BONE_SELECTED;
02553             pchan->bone->flag |= pchan->selectflag;
02554         }
02555     }
02556     
02557     if(rebuild) {
02558         ob->recalc= OB_RECALC_OB|OB_RECALC_DATA|OB_RECALC_TIME;
02559         pose->flag |= POSE_RECALC;
02560     }
02561 }
02562 
02563 static void lib_link_armature(FileData *fd, Main *main)
02564 {
02565     bArmature *arm;
02566 
02567     arm= main->armature.first;
02568 
02569     while(arm) {
02570         if(arm->id.flag & LIB_NEEDLINK) {
02571             if (arm->adt) lib_link_animdata(fd, &arm->id, arm->adt);
02572             arm->id.flag -= LIB_NEEDLINK;
02573         }
02574         arm= arm->id.next;
02575     }
02576 }
02577 
02578 static void direct_link_bones(FileData *fd, Bone* bone)
02579 {
02580     Bone    *child;
02581 
02582     bone->parent= newdataadr(fd, bone->parent);
02583     bone->prop= newdataadr(fd, bone->prop);
02584     if(bone->prop)
02585         IDP_DirectLinkProperty(bone->prop, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
02586         
02587     bone->flag &= ~BONE_DRAW_ACTIVE;
02588 
02589     link_list(fd, &bone->childbase);
02590 
02591     for(child=bone->childbase.first; child; child=child->next)
02592         direct_link_bones(fd, child);
02593 }
02594 
02595 static void direct_link_armature(FileData *fd, bArmature *arm)
02596 {
02597     Bone    *bone;
02598 
02599     link_list(fd, &arm->bonebase);
02600     arm->edbo= NULL;
02601     arm->sketch = NULL;
02602     
02603     arm->adt= newdataadr(fd, arm->adt);
02604     direct_link_animdata(fd, arm->adt);
02605     
02606     bone=arm->bonebase.first;
02607     while (bone) {
02608         direct_link_bones(fd, bone);
02609         bone=bone->next;
02610     }
02611 
02612     arm->act_bone= newdataadr(fd, arm->act_bone);
02613     arm->act_edbone= NULL;
02614 }
02615 
02616 /* ************ READ CAMERA ***************** */
02617 
02618 static void lib_link_camera(FileData *fd, Main *main)
02619 {
02620     Camera *ca;
02621 
02622     ca= main->camera.first;
02623     while(ca) {
02624         if(ca->id.flag & LIB_NEEDLINK) {
02625             if (ca->adt) lib_link_animdata(fd, &ca->id, ca->adt);
02626             
02627             ca->ipo= newlibadr_us(fd, ca->id.lib, ca->ipo); // XXX depreceated - old animation system
02628             
02629             ca->dof_ob= newlibadr_us(fd, ca->id.lib, ca->dof_ob);
02630             
02631             ca->id.flag -= LIB_NEEDLINK;
02632         }
02633         ca= ca->id.next;
02634     }
02635 }
02636 
02637 static void direct_link_camera(FileData *fd, Camera *ca)
02638 {
02639     ca->adt= newdataadr(fd, ca->adt);
02640     direct_link_animdata(fd, ca->adt);
02641 }
02642 
02643 
02644 /* ************ READ LAMP ***************** */
02645 
02646 static void lib_link_lamp(FileData *fd, Main *main)
02647 {
02648     Lamp *la;
02649     MTex *mtex;
02650     int a;
02651 
02652     la= main->lamp.first;
02653     while(la) {
02654         if(la->id.flag & LIB_NEEDLINK) {
02655             if (la->adt) lib_link_animdata(fd, &la->id, la->adt);
02656             
02657             for(a=0; a<MAX_MTEX; a++) {
02658                 mtex= la->mtex[a];
02659                 if(mtex) {
02660                     mtex->tex= newlibadr_us(fd, la->id.lib, mtex->tex);
02661                     mtex->object= newlibadr(fd, la->id.lib, mtex->object);
02662                 }
02663             }
02664             
02665             la->ipo= newlibadr_us(fd, la->id.lib, la->ipo); // XXX depreceated - old animation system
02666 
02667             if(la->nodetree)
02668                 lib_link_ntree(fd, &la->id, la->nodetree);
02669             
02670             la->id.flag -= LIB_NEEDLINK;
02671         }
02672         la= la->id.next;
02673     }
02674 }
02675 
02676 static void direct_link_lamp(FileData *fd, Lamp *la)
02677 {
02678     int a;
02679     
02680     la->adt= newdataadr(fd, la->adt);
02681     direct_link_animdata(fd, la->adt);
02682 
02683     for(a=0; a<MAX_MTEX; a++) {
02684         la->mtex[a]= newdataadr(fd, la->mtex[a]);
02685     }
02686     
02687     la->curfalloff= newdataadr(fd, la->curfalloff);
02688     if(la->curfalloff)
02689         direct_link_curvemapping(fd, la->curfalloff);
02690 
02691     la->nodetree= newdataadr(fd, la->nodetree);
02692     if(la->nodetree)
02693         direct_link_nodetree(fd, la->nodetree);
02694     
02695     la->preview = direct_link_preview_image(fd, la->preview);
02696 }
02697 
02698 /* ************ READ keys ***************** */
02699 
02700 static void lib_link_key(FileData *fd, Main *main)
02701 {
02702     Key *key;
02703 
02704     key= main->key.first;
02705     while(key) {
02706         if(key->id.flag & LIB_NEEDLINK) {
02707             if(key->adt) lib_link_animdata(fd, &key->id, key->adt);
02708             
02709             key->ipo= newlibadr_us(fd, key->id.lib, key->ipo); // XXX depreceated - old animation system
02710             key->from= newlibadr(fd, key->id.lib, key->from);
02711 
02712             key->id.flag -= LIB_NEEDLINK;
02713         }
02714         key= key->id.next;
02715     }
02716 }
02717 
02718 static void switch_endian_keyblock(Key *key, KeyBlock *kb)
02719 {
02720     int elemsize, a, b;
02721     char *data, *poin, *cp;
02722 
02723     elemsize= key->elemsize;
02724     data= kb->data;
02725 
02726     for(a=0; a<kb->totelem; a++) {
02727 
02728         cp= key->elemstr;
02729         poin= data;
02730 
02731         while( cp[0] ) {    /* cp[0]==amount */
02732 
02733             switch(cp[1]) {     /* cp[1]= type */
02734             case IPO_FLOAT:
02735             case IPO_BPOINT:
02736             case IPO_BEZTRIPLE:
02737                 b= cp[0];
02738                 while(b--) {
02739                     SWITCH_INT((*poin));
02740                     poin+= 4;
02741                 }
02742                 break;
02743             }
02744 
02745             cp+= 2;
02746 
02747         }
02748         data+= elemsize;
02749     }
02750 }
02751 
02752 static void direct_link_key(FileData *fd, Key *key)
02753 {
02754     KeyBlock *kb;
02755 
02756     link_list(fd, &(key->block));
02757 
02758     key->adt= newdataadr(fd, key->adt);
02759     direct_link_animdata(fd, key->adt);
02760     
02761     key->refkey= newdataadr(fd, key->refkey);
02762 
02763     kb= key->block.first;
02764     while(kb) {
02765 
02766         kb->data= newdataadr(fd, kb->data);
02767         
02768         if(fd->flags & FD_FLAGS_SWITCH_ENDIAN)
02769             switch_endian_keyblock(key, kb);
02770 
02771         kb= kb->next;
02772     }
02773 }
02774 
02775 /* ************ READ mball ***************** */
02776 
02777 static void lib_link_mball(FileData *fd, Main *main)
02778 {
02779     MetaBall *mb;
02780     int a;
02781 
02782     mb= main->mball.first;
02783     while(mb) {
02784         if(mb->id.flag & LIB_NEEDLINK) {
02785             if (mb->adt) lib_link_animdata(fd, &mb->id, mb->adt);
02786             
02787             for(a=0; a<mb->totcol; a++) mb->mat[a]= newlibadr_us(fd, mb->id.lib, mb->mat[a]);
02788 
02789             mb->ipo= newlibadr_us(fd, mb->id.lib, mb->ipo); // XXX depreceated - old animation system
02790 
02791             mb->id.flag -= LIB_NEEDLINK;
02792         }
02793         mb= mb->id.next;
02794     }
02795 }
02796 
02797 static void direct_link_mball(FileData *fd, MetaBall *mb)
02798 {
02799     mb->adt= newdataadr(fd, mb->adt);
02800     direct_link_animdata(fd, mb->adt);
02801     
02802     mb->mat= newdataadr(fd, mb->mat);
02803     test_pointer_array(fd, (void **)&mb->mat);
02804 
02805     link_list(fd, &(mb->elems));
02806 
02807     mb->disp.first= mb->disp.last= NULL;
02808     mb->editelems= NULL;
02809     mb->bb= NULL;
02810 /*  mb->edit_elems.first= mb->edit_elems.last= NULL;*/
02811     mb->lastelem= NULL;
02812 }
02813 
02814 /* ************ READ WORLD ***************** */
02815 
02816 static void lib_link_world(FileData *fd, Main *main)
02817 {
02818     World *wrld;
02819     MTex *mtex;
02820     int a;
02821 
02822     wrld= main->world.first;
02823     while(wrld) {
02824         if(wrld->id.flag & LIB_NEEDLINK) {
02825             if (wrld->adt) lib_link_animdata(fd, &wrld->id, wrld->adt);
02826             
02827             wrld->ipo= newlibadr_us(fd, wrld->id.lib, wrld->ipo); // XXX depreceated - old animation system
02828             
02829             for(a=0; a<MAX_MTEX; a++) {
02830                 mtex= wrld->mtex[a];
02831                 if(mtex) {
02832                     mtex->tex= newlibadr_us(fd, wrld->id.lib, mtex->tex);
02833                     mtex->object= newlibadr(fd, wrld->id.lib, mtex->object);
02834                 }
02835             }
02836 
02837             if(wrld->nodetree)
02838                 lib_link_ntree(fd, &wrld->id, wrld->nodetree);
02839             
02840             wrld->id.flag -= LIB_NEEDLINK;
02841         }
02842         wrld= wrld->id.next;
02843     }
02844 }
02845 
02846 static void direct_link_world(FileData *fd, World *wrld)
02847 {
02848     int a;
02849 
02850     wrld->adt= newdataadr(fd, wrld->adt);
02851     direct_link_animdata(fd, wrld->adt);
02852 
02853     for(a=0; a<MAX_MTEX; a++) {
02854         wrld->mtex[a]= newdataadr(fd, wrld->mtex[a]);
02855     }
02856 
02857     wrld->nodetree= newdataadr(fd, wrld->nodetree);
02858     if(wrld->nodetree)
02859         direct_link_nodetree(fd, wrld->nodetree);
02860 
02861     wrld->preview = direct_link_preview_image(fd, wrld->preview);
02862 }
02863 
02864 
02865 /* ************ READ VFONT ***************** */
02866 
02867 static void lib_link_vfont(FileData *UNUSED(fd), Main *main)
02868 {
02869     VFont *vf;
02870 
02871     vf= main->vfont.first;
02872     while(vf) {
02873         if(vf->id.flag & LIB_NEEDLINK) {
02874             vf->id.flag -= LIB_NEEDLINK;
02875         }
02876         vf= vf->id.next;
02877     }
02878 }
02879 
02880 static void direct_link_vfont(FileData *fd, VFont *vf)
02881 {
02882     vf->data= NULL;
02883     vf->packedfile= direct_link_packedfile(fd, vf->packedfile);
02884 }
02885 
02886 /* ************ READ TEXT ****************** */
02887 
02888 static void lib_link_text(FileData *UNUSED(fd), Main *main)
02889 {
02890     Text *text;
02891 
02892     text= main->text.first;
02893     while(text) {
02894         if(text->id.flag & LIB_NEEDLINK) {
02895             text->id.flag -= LIB_NEEDLINK;
02896         }
02897         text= text->id.next;
02898     }
02899 }
02900 
02901 static void direct_link_text(FileData *fd, Text *text)
02902 {
02903     TextLine *ln;
02904 
02905     text->name= newdataadr(fd, text->name);
02906 
02907     text->undo_pos= -1;
02908     text->undo_len= TXT_INIT_UNDO;
02909     text->undo_buf= MEM_mallocN(text->undo_len, "undo buf");
02910 
02911     text->compiled= NULL;
02912 
02913 /*
02914     if(text->flags & TXT_ISEXT) {
02915         reopen_text(text);
02916     } else {
02917 */
02918 
02919     link_list(fd, &text->lines);
02920     link_list(fd, &text->markers);
02921 
02922     text->curl= newdataadr(fd, text->curl);
02923     text->sell= newdataadr(fd, text->sell);
02924 
02925     ln= text->lines.first;
02926     while(ln) {
02927         ln->line= newdataadr(fd, ln->line);
02928         ln->format= NULL;
02929         
02930         if (ln->len != (int) strlen(ln->line)) {
02931             printf("Error loading text, line lengths differ\n");
02932             ln->len = strlen(ln->line);
02933         }
02934 
02935         ln= ln->next;
02936     }
02937 
02938     text->flags = (text->flags) & ~TXT_ISEXT;
02939 
02940     text->id.us= 1;
02941 }
02942 
02943 /* ************ READ IMAGE ***************** */
02944 
02945 static void lib_link_image(FileData *fd, Main *main)
02946 {
02947     Image *ima;
02948 
02949     ima= main->image.first;
02950     while (ima) {
02951         if(ima->id.flag & LIB_NEEDLINK) {
02952             if (ima->id.properties) IDP_LibLinkProperty(ima->id.properties, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
02953 
02954             ima->id.flag -= LIB_NEEDLINK;
02955         }
02956         ima= ima->id.next;
02957     }
02958 }
02959 
02960 static void link_ibuf_list(FileData *fd, ListBase *lb)
02961 {
02962     Link *ln, *prev;
02963     
02964     if(lb->first==NULL) return;
02965     
02966     lb->first= newimaadr(fd, lb->first);
02967     ln= lb->first;
02968     prev= NULL;
02969     while(ln) {
02970         ln->next= newimaadr(fd, ln->next);
02971         ln->prev= prev;
02972         prev= ln;
02973         ln= ln->next;
02974     }
02975     lb->last= prev;
02976 }
02977 
02978 static void direct_link_image(FileData *fd, Image *ima)
02979 {
02980     /* for undo system, pointers could be restored */
02981     if(fd->imamap)
02982         link_ibuf_list(fd, &ima->ibufs);
02983     else
02984         ima->ibufs.first= ima->ibufs.last= NULL;
02985     
02986     /* if not restored, we keep the binded opengl index */
02987     if(ima->ibufs.first==NULL) {
02988         ima->bindcode= 0;
02989         ima->gputexture= NULL;
02990     }
02991     
02992     ima->anim= NULL;
02993     ima->rr= NULL;
02994     ima->repbind= NULL;
02995     
02996     /* undo system, try to restore render buffers */
02997     if(fd->imamap) {
02998         int a;
02999         
03000         for(a=0; a<IMA_MAX_RENDER_SLOT; a++)
03001             ima->renders[a]= newimaadr(fd, ima->renders[a]);
03002     }
03003     else {
03004         memset(ima->renders, 0, sizeof(ima->renders));
03005         ima->last_render_slot= ima->render_slot;
03006     }
03007     
03008     ima->packedfile = direct_link_packedfile(fd, ima->packedfile);
03009     ima->preview = direct_link_preview_image(fd, ima->preview);
03010     ima->ok= 1;
03011 }
03012 
03013 
03014 /* ************ READ CURVE ***************** */
03015 
03016 static void lib_link_curve(FileData *fd, Main *main)
03017 {
03018     Curve *cu;
03019     int a;
03020 
03021     cu= main->curve.first;
03022     while(cu) {
03023         if(cu->id.flag & LIB_NEEDLINK) {
03024             if(cu->adt) lib_link_animdata(fd, &cu->id, cu->adt);
03025 
03026             for(a=0; a<cu->totcol; a++) cu->mat[a]= newlibadr_us(fd, cu->id.lib, cu->mat[a]);
03027 
03028             cu->bevobj= newlibadr(fd, cu->id.lib, cu->bevobj);
03029             cu->taperobj= newlibadr(fd, cu->id.lib, cu->taperobj);
03030             cu->textoncurve= newlibadr(fd, cu->id.lib, cu->textoncurve);
03031             cu->vfont= newlibadr_us(fd, cu->id.lib, cu->vfont);
03032             cu->vfontb= newlibadr_us(fd, cu->id.lib, cu->vfontb);           
03033             cu->vfonti= newlibadr_us(fd, cu->id.lib, cu->vfonti);
03034             cu->vfontbi= newlibadr_us(fd, cu->id.lib, cu->vfontbi);
03035 
03036             cu->ipo= newlibadr_us(fd, cu->id.lib, cu->ipo); // XXX depreceated - old animation system
03037             cu->key= newlibadr_us(fd, cu->id.lib, cu->key);
03038 
03039             cu->id.flag -= LIB_NEEDLINK;
03040         }
03041         cu= cu->id.next;
03042     }
03043 }
03044 
03045 
03046 static void switch_endian_knots(Nurb *nu)
03047 {
03048     int len;
03049 
03050     if(nu->knotsu) {
03051         len= KNOTSU(nu);
03052         while(len--) {
03053             SWITCH_INT(nu->knotsu[len]);
03054         }
03055     }
03056     if(nu->knotsv) {
03057         len= KNOTSV(nu);
03058         while(len--) {
03059             SWITCH_INT(nu->knotsv[len]);
03060         }
03061     }
03062 }
03063 
03064 static void direct_link_curve(FileData *fd, Curve *cu)
03065 {
03066     Nurb *nu;
03067     TextBox *tb;
03068     
03069     cu->adt= newdataadr(fd, cu->adt);
03070     direct_link_animdata(fd, cu->adt);
03071     
03072     cu->mat= newdataadr(fd, cu->mat);
03073     test_pointer_array(fd, (void **)&cu->mat);
03074     cu->str= newdataadr(fd, cu->str);
03075     cu->strinfo= newdataadr(fd, cu->strinfo);   
03076     cu->tb= newdataadr(fd, cu->tb);
03077 
03078     if(cu->vfont == NULL) link_list(fd, &(cu->nurb));
03079     else {
03080         cu->nurb.first=cu->nurb.last= NULL;
03081 
03082         tb= MEM_callocN(MAXTEXTBOX*sizeof(TextBox), "TextBoxread");
03083         if (cu->tb) {
03084             memcpy(tb, cu->tb, cu->totbox*sizeof(TextBox));
03085             MEM_freeN(cu->tb);
03086             cu->tb= tb;         
03087         } else {
03088             cu->totbox = 1;
03089             cu->actbox = 1;
03090             cu->tb = tb;
03091             cu->tb[0].w = cu->linewidth;
03092         }       
03093         if (cu->wordspace == 0.0f) cu->wordspace = 1.0f;
03094     }
03095 
03096     cu->bev.first=cu->bev.last= NULL;
03097     cu->disp.first=cu->disp.last= NULL;
03098     cu->editnurb= NULL;
03099     cu->lastsel= NULL;
03100     cu->path= NULL;
03101     cu->editfont= NULL;
03102     
03103     nu= cu->nurb.first;
03104     while(nu) {
03105         nu->bezt= newdataadr(fd, nu->bezt);
03106         nu->bp= newdataadr(fd, nu->bp);
03107         nu->knotsu= newdataadr(fd, nu->knotsu);
03108         nu->knotsv= newdataadr(fd, nu->knotsv);
03109         if (cu->vfont == NULL) nu->charidx= nu->mat_nr;
03110 
03111         if(fd->flags & FD_FLAGS_SWITCH_ENDIAN) {
03112             switch_endian_knots(nu);
03113         }
03114 
03115         nu= nu->next;
03116     }
03117     cu->bb= NULL;
03118 }
03119 
03120 /* ************ READ TEX ***************** */
03121 
03122 static void lib_link_texture(FileData *fd, Main *main)
03123 {
03124     Tex *tex;
03125 
03126     tex= main->tex.first;
03127     while(tex) {
03128         if(tex->id.flag & LIB_NEEDLINK) {
03129             if(tex->adt) lib_link_animdata(fd, &tex->id, tex->adt);
03130 
03131             tex->ima= newlibadr_us(fd, tex->id.lib, tex->ima);
03132             tex->ipo= newlibadr_us(fd, tex->id.lib, tex->ipo);
03133             if(tex->env) tex->env->object= newlibadr(fd, tex->id.lib, tex->env->object);
03134             if(tex->pd)
03135                 tex->pd->object= newlibadr(fd, tex->id.lib, tex->pd->object);
03136             if(tex->vd) tex->vd->object= newlibadr(fd, tex->id.lib, tex->vd->object);
03137             if(tex->ot) tex->ot->object= newlibadr(fd, tex->id.lib, tex->ot->object);
03138                 
03139 
03140             if(tex->nodetree)
03141                 lib_link_ntree(fd, &tex->id, tex->nodetree);
03142             
03143             tex->id.flag -= LIB_NEEDLINK;
03144         }
03145         tex= tex->id.next;
03146     }
03147 }
03148 
03149 static void direct_link_texture(FileData *fd, Tex *tex)
03150 {
03151     tex->adt= newdataadr(fd, tex->adt);
03152     direct_link_animdata(fd, tex->adt);
03153     
03154     tex->plugin= newdataadr(fd, tex->plugin);
03155     if(tex->plugin) {
03156         tex->plugin->handle= NULL;
03157         open_plugin_tex(tex->plugin);
03158         /* initialize data for this instance, if an initialization
03159          * function exists.
03160          */
03161         if (tex->plugin->instance_init)
03162             tex->plugin->instance_init((void *) tex->plugin->data);
03163     }
03164     tex->coba= newdataadr(fd, tex->coba);
03165     tex->env= newdataadr(fd, tex->env);
03166     if(tex->env) {
03167         tex->env->ima= NULL;
03168         memset(tex->env->cube, 0, 6*sizeof(void *));
03169         tex->env->ok= 0;
03170     }
03171     tex->pd= newdataadr(fd, tex->pd);
03172     if(tex->pd) {
03173         tex->pd->point_tree = NULL;
03174         tex->pd->coba= newdataadr(fd, tex->pd->coba);
03175         tex->pd->falloff_curve= newdataadr(fd, tex->pd->falloff_curve);
03176         if(tex->pd->falloff_curve) {
03177             direct_link_curvemapping(fd, tex->pd->falloff_curve);
03178         }
03179     }
03180     
03181     tex->vd= newdataadr(fd, tex->vd);
03182     if(tex->vd) {
03183         tex->vd->dataset = NULL;
03184         tex->vd->ok = 0;
03185     } else {
03186         if(tex->type == TEX_VOXELDATA)
03187             tex->vd= MEM_callocN(sizeof(VoxelData), "direct_link_texture VoxelData");
03188     }
03189     
03190     tex->ot= newdataadr(fd, tex->ot);
03191     
03192     tex->nodetree= newdataadr(fd, tex->nodetree);
03193     if(tex->nodetree)
03194         direct_link_nodetree(fd, tex->nodetree);
03195     
03196     tex->preview = direct_link_preview_image(fd, tex->preview);
03197 
03198     tex->iuser.ok= 1;
03199 }
03200 
03201 
03202 
03203 /* ************ READ MATERIAL ***************** */
03204 
03205 static void lib_link_material(FileData *fd, Main *main)
03206 {
03207     Material *ma;
03208     MTex *mtex;
03209     int a;
03210 
03211     ma= main->mat.first;
03212     while(ma) {
03213         if(ma->id.flag & LIB_NEEDLINK) {
03214             if(ma->adt) lib_link_animdata(fd, &ma->id, ma->adt);
03215 
03216             /*Link ID Properties -- and copy this comment EXACTLY for easy finding
03217             of library blocks that implement this.*/
03218             if (ma->id.properties) IDP_LibLinkProperty(ma->id.properties, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
03219 
03220             ma->ipo= newlibadr_us(fd, ma->id.lib, ma->ipo);
03221             ma->group= newlibadr_us(fd, ma->id.lib, ma->group);
03222             
03223             for(a=0; a<MAX_MTEX; a++) {
03224                 mtex= ma->mtex[a];
03225                 if(mtex) {
03226                     mtex->tex= newlibadr_us(fd, ma->id.lib, mtex->tex);
03227                     mtex->object= newlibadr(fd, ma->id.lib, mtex->object);
03228                 }
03229             }
03230             
03231             if(ma->nodetree)
03232                 lib_link_ntree(fd, &ma->id, ma->nodetree);
03233             
03234             ma->id.flag -= LIB_NEEDLINK;
03235         }
03236         ma= ma->id.next;
03237     }
03238 }
03239 
03240 static void direct_link_material(FileData *fd, Material *ma)
03241 {
03242     int a;
03243 
03244     ma->adt= newdataadr(fd, ma->adt);
03245     direct_link_animdata(fd, ma->adt);
03246     
03247     for(a=0; a<MAX_MTEX; a++) {
03248         ma->mtex[a]= newdataadr(fd, ma->mtex[a]);
03249     }
03250 
03251     ma->ramp_col= newdataadr(fd, ma->ramp_col);
03252     ma->ramp_spec= newdataadr(fd, ma->ramp_spec);
03253     
03254     ma->nodetree= newdataadr(fd, ma->nodetree);
03255     if(ma->nodetree)
03256         direct_link_nodetree(fd, ma->nodetree);
03257 
03258     ma->preview = direct_link_preview_image(fd, ma->preview);
03259     ma->gpumaterial.first = ma->gpumaterial.last = NULL;
03260 }
03261 
03262 /* ************ READ PARTICLE SETTINGS ***************** */
03263 /* update this also to writefile.c */
03264 static const char *ptcache_data_struct[] = {
03265     "", // BPHYS_DATA_INDEX
03266     "", // BPHYS_DATA_LOCATION
03267     "", // BPHYS_DATA_VELOCITY
03268     "", // BPHYS_DATA_ROTATION
03269     "", // BPHYS_DATA_AVELOCITY / BPHYS_DATA_XCONST */
03270     "", // BPHYS_DATA_SIZE:
03271     "", // BPHYS_DATA_TIMES:    
03272     "BoidData" // case BPHYS_DATA_BOIDS:
03273 };
03274 static void direct_link_pointcache(FileData *fd, PointCache *cache)
03275 {
03276     if((cache->flag & PTCACHE_DISK_CACHE)==0) {
03277         PTCacheMem *pm;
03278         PTCacheExtra *extra;
03279         int i;
03280 
03281         link_list(fd, &cache->mem_cache);
03282 
03283         pm = cache->mem_cache.first;
03284 
03285         for(; pm; pm=pm->next) {
03286             for(i=0; i<BPHYS_TOT_DATA; i++) {
03287                 pm->data[i] = newdataadr(fd, pm->data[i]);
03288                 
03289                 /* the cache saves non-struct data without DNA */
03290                 if(pm->data[i] && ptcache_data_struct[i][0]=='\0' && (fd->flags & FD_FLAGS_SWITCH_ENDIAN)) {
03291                     int j, tot= (BKE_ptcache_data_size (i) * pm->totpoint)/4; /* data_size returns bytes */
03292                     int *poin= pm->data[i];
03293                     
03294                     for(j= 0; j<tot; j++)
03295                         SWITCH_INT(poin[j]);
03296                 }
03297             }
03298             
03299             link_list(fd, &pm->extradata);
03300 
03301             for(extra=pm->extradata.first; extra; extra=extra->next)
03302                 extra->data = newdataadr(fd, extra->data);
03303         }
03304     }
03305     else
03306         cache->mem_cache.first = cache->mem_cache.last = NULL;
03307 
03308     cache->flag &= ~PTCACHE_SIMULATION_VALID;
03309     cache->simframe= 0;
03310     cache->edit= NULL;
03311     cache->free_edit= NULL;
03312     cache->cached_frames= NULL;
03313 }
03314 
03315 static void direct_link_pointcache_list(FileData *fd, ListBase *ptcaches, PointCache **ocache, int force_disk)
03316 {
03317     if(ptcaches->first) {
03318         PointCache *cache= NULL;
03319         link_list(fd, ptcaches);
03320         for(cache=ptcaches->first; cache; cache=cache->next) {
03321             direct_link_pointcache(fd, cache);
03322             if(force_disk) {
03323                 cache->flag |= PTCACHE_DISK_CACHE;
03324                 cache->step = 1;
03325             }
03326         }
03327 
03328         *ocache = newdataadr(fd, *ocache);
03329     }
03330     else if(*ocache) {
03331         /* old "single" caches need to be linked too */
03332         *ocache = newdataadr(fd, *ocache);
03333         direct_link_pointcache(fd, *ocache);
03334         if(force_disk) {
03335             (*ocache)->flag |= PTCACHE_DISK_CACHE;
03336             (*ocache)->step = 1;
03337         }
03338 
03339         ptcaches->first = ptcaches->last = *ocache;
03340     }
03341 }
03342 
03343 static void lib_link_partdeflect(FileData *fd, ID *id, PartDeflect *pd)
03344 {
03345     if(pd && pd->tex)
03346         pd->tex=newlibadr_us(fd, id->lib, pd->tex);
03347 }
03348 
03349 static void lib_link_particlesettings(FileData *fd, Main *main)
03350 {
03351     ParticleSettings *part;
03352     ParticleDupliWeight *dw;
03353     MTex *mtex;
03354     int a;
03355 
03356     part= main->particle.first;
03357     while(part) {
03358         if(part->id.flag & LIB_NEEDLINK) {
03359             if (part->adt) lib_link_animdata(fd, &part->id, part->adt);
03360             part->ipo= newlibadr_us(fd, part->id.lib, part->ipo); // XXX depreceated - old animation system
03361             
03362             part->dup_ob = newlibadr(fd, part->id.lib, part->dup_ob);
03363             part->dup_group = newlibadr(fd, part->id.lib, part->dup_group);
03364             part->eff_group = newlibadr(fd, part->id.lib, part->eff_group);
03365             part->bb_ob = newlibadr(fd, part->id.lib, part->bb_ob);
03366 
03367             lib_link_partdeflect(fd, &part->id, part->pd);
03368             lib_link_partdeflect(fd, &part->id, part->pd2);
03369 
03370             if(part->effector_weights)
03371                 part->effector_weights->group = newlibadr(fd, part->id.lib, part->effector_weights->group);
03372 
03373             if(part->dupliweights.first && part->dup_group) {
03374                 int index_ok = 0;
03375                 /* check for old files without indices (all indexes 0) */
03376                 dw = part->dupliweights.first;
03377                 if(part->dupliweights.first == part->dupliweights.last) {
03378                     /* special case for only one object in the group */
03379                     index_ok = 1;
03380                 }
03381                 else { 
03382                     for(; dw; dw=dw->next) {
03383                         if(dw->index > 0) {
03384                             index_ok = 1;
03385                             break;
03386                         }
03387                     }
03388                 }
03389 
03390                 if(index_ok) {
03391                     /* if we have indexes, let's use them */
03392                     dw = part->dupliweights.first;
03393                     for(; dw; dw=dw->next) {
03394                         GroupObject *go = (GroupObject *)BLI_findlink(&part->dup_group->gobject, dw->index);
03395                         dw->ob = go ? go->ob : NULL;
03396                     }
03397                 }
03398                 else {
03399                     /* otherwise try to get objects from own library (won't work on library linked groups) */
03400                     for(; dw; dw=dw->next)
03401                         dw->ob = newlibadr(fd, part->id.lib, dw->ob);
03402                 }
03403             }
03404             else {
03405                 part->dupliweights.first = part->dupliweights.last = NULL;
03406             }
03407 
03408             if(part->boids) {
03409                 BoidState *state = part->boids->states.first;
03410                 BoidRule *rule;
03411                 for(; state; state=state->next) {
03412                     rule = state->rules.first;
03413                 for(; rule; rule=rule->next)
03414                     switch(rule->type) {
03415                         case eBoidRuleType_Goal:
03416                         case eBoidRuleType_Avoid:
03417                         {
03418                             BoidRuleGoalAvoid *brga = (BoidRuleGoalAvoid*)rule;
03419                             brga->ob = newlibadr(fd, part->id.lib, brga->ob);
03420                             break;
03421                         }
03422                         case eBoidRuleType_FollowLeader:
03423                         {
03424                             BoidRuleFollowLeader *brfl = (BoidRuleFollowLeader*)rule;
03425                             brfl->ob = newlibadr(fd, part->id.lib, brfl->ob);
03426                             break;
03427                         }
03428                     }
03429                 }
03430             }
03431             
03432             for(a=0; a<MAX_MTEX; a++) {
03433                 mtex= part->mtex[a];
03434                 if(mtex) {
03435                     mtex->tex = newlibadr_us(fd, part->id.lib, mtex->tex);
03436                     mtex->object = newlibadr(fd, part->id.lib, mtex->object);
03437                 }
03438             }
03439 
03440             part->id.flag -= LIB_NEEDLINK;
03441         }
03442         part= part->id.next;
03443     }
03444 }
03445 
03446 static void direct_link_partdeflect(PartDeflect *pd)
03447 {
03448     if(pd) pd->rng=NULL;
03449 }
03450 
03451 static void direct_link_particlesettings(FileData *fd, ParticleSettings *part)
03452 {
03453     int a;
03454     part->adt= newdataadr(fd, part->adt);
03455     part->pd= newdataadr(fd, part->pd);
03456     part->pd2= newdataadr(fd, part->pd2);
03457 
03458     direct_link_animdata(fd, part->adt);
03459     direct_link_partdeflect(part->pd);
03460     direct_link_partdeflect(part->pd2);
03461 
03462     part->effector_weights = newdataadr(fd, part->effector_weights);
03463     if(!part->effector_weights)
03464         part->effector_weights = BKE_add_effector_weights(part->eff_group);
03465 
03466     link_list(fd, &part->dupliweights);
03467 
03468     part->boids= newdataadr(fd, part->boids);
03469     part->fluid= newdataadr(fd, part->fluid);
03470 
03471     if(part->boids) {
03472         BoidState *state;
03473         link_list(fd, &part->boids->states);
03474         
03475         for(state=part->boids->states.first; state; state=state->next) {
03476             link_list(fd, &state->rules);
03477             link_list(fd, &state->conditions);
03478             link_list(fd, &state->actions);
03479         }
03480     }
03481     for(a=0; a<MAX_MTEX; a++) {
03482         part->mtex[a]= newdataadr(fd, part->mtex[a]);
03483     }
03484 }
03485 
03486 static void lib_link_particlesystems(FileData *fd, Object *ob, ID *id, ListBase *particles)
03487 {
03488     ParticleSystem *psys, *psysnext;
03489 
03490     for(psys=particles->first; psys; psys=psysnext){
03491         psysnext= psys->next;
03492         
03493         psys->part = newlibadr_us(fd, id->lib, psys->part);
03494         if(psys->part) {
03495             ParticleTarget *pt = psys->targets.first;
03496 
03497             for(; pt; pt=pt->next)
03498                 pt->ob=newlibadr(fd, id->lib, pt->ob);
03499 
03500             psys->parent= newlibadr_us(fd, id->lib, psys->parent);
03501             psys->target_ob = newlibadr(fd, id->lib, psys->target_ob);
03502 
03503             if(psys->clmd) {
03504                 /* XXX - from reading existing code this seems correct but intended usage of
03505                  * pointcache should /w cloth should be added in 'ParticleSystem' - campbell */
03506                 psys->clmd->point_cache= psys->pointcache;
03507                 psys->clmd->ptcaches.first= psys->clmd->ptcaches.last= NULL;
03508                 psys->clmd->coll_parms->group= newlibadr(fd, id->lib, psys->clmd->coll_parms->group);
03509             }
03510         }
03511         else {
03512             /* particle modifier must be removed before particle system */
03513             ParticleSystemModifierData *psmd= psys_get_modifier(ob,psys);
03514             BLI_remlink(&ob->modifiers, psmd);
03515             modifier_free((ModifierData *)psmd);
03516 
03517             BLI_remlink(particles, psys);
03518             MEM_freeN(psys);
03519         }
03520     }
03521 }
03522 static void direct_link_particlesystems(FileData *fd, ListBase *particles)
03523 {
03524     ParticleSystem *psys;
03525     ParticleData *pa;
03526     int a;
03527 
03528     for(psys=particles->first; psys; psys=psys->next) {
03529         psys->particles=newdataadr(fd,psys->particles);
03530         
03531         if(psys->particles && psys->particles->hair){
03532             for(a=0,pa=psys->particles; a<psys->totpart; a++, pa++)
03533                 pa->hair=newdataadr(fd,pa->hair);
03534         }
03535         
03536         if(psys->particles && psys->particles->keys){
03537             for(a=0,pa=psys->particles; a<psys->totpart; a++, pa++) {
03538                 pa->keys= NULL;
03539                 pa->totkey= 0;
03540             }
03541 
03542             psys->flag &= ~PSYS_KEYED;
03543         }
03544 
03545         if(psys->particles && psys->particles->boid) {
03546             pa = psys->particles;
03547             pa->boid = newdataadr(fd, pa->boid);
03548             for(a=1,pa++; a<psys->totpart; a++, pa++)
03549                 pa->boid = (pa-1)->boid + 1;
03550         }
03551         else if(psys->particles) {
03552             for(a=0,pa=psys->particles; a<psys->totpart; a++, pa++)
03553                 pa->boid = NULL;
03554         }
03555 
03556         psys->fluid_springs = newdataadr(fd, psys->fluid_springs);
03557 
03558         psys->child = newdataadr(fd,psys->child);
03559         psys->effectors = NULL;
03560 
03561         link_list(fd, &psys->targets);
03562 
03563         psys->edit = NULL;
03564         psys->free_edit = NULL;
03565         psys->pathcache = NULL;
03566         psys->childcache = NULL;
03567         psys->pathcachebufs.first = psys->pathcachebufs.last = NULL;
03568         psys->childcachebufs.first = psys->childcachebufs.last = NULL;
03569         psys->frand = NULL;
03570         psys->pdd = NULL;
03571         psys->renderdata = NULL;
03572         
03573         direct_link_pointcache_list(fd, &psys->ptcaches, &psys->pointcache, 0);
03574 
03575         if(psys->clmd) {
03576             psys->clmd = newdataadr(fd, psys->clmd);
03577             psys->clmd->clothObject = NULL;
03578             
03579             psys->clmd->sim_parms= newdataadr(fd, psys->clmd->sim_parms);
03580             psys->clmd->sim_parms->effector_weights = NULL;
03581             psys->clmd->coll_parms= newdataadr(fd, psys->clmd->coll_parms);
03582             
03583             if(psys->clmd->sim_parms) {
03584                 if(psys->clmd->sim_parms->presets > 10)
03585                     psys->clmd->sim_parms->presets = 0;
03586             }
03587 
03588             psys->hair_in_dm = psys->hair_out_dm = NULL;
03589 
03590             psys->clmd->point_cache = psys->pointcache;
03591         }
03592 
03593         psys->tree = NULL;
03594         psys->bvhtree = NULL;
03595     }
03596     return;
03597 }
03598 
03599 /* ************ READ MESH ***************** */
03600 
03601 static void lib_link_mtface(FileData *fd, Mesh *me, MTFace *mtface, int totface)
03602 {
03603     MTFace *tf= mtface;
03604     int i;
03605 
03606     /* Add pseudo-references (not fake users!) to images used by texface. A
03607      * little bogus; it would be better if each mesh consistently added one ref
03608      * to each image it used. - z0r */
03609     for (i=0; i<totface; i++, tf++) {
03610         tf->tpage= newlibadr(fd, me->id.lib, tf->tpage);
03611         if(tf->tpage && tf->tpage->id.us==0)
03612             tf->tpage->id.us= 1;
03613     }
03614 }
03615 
03616 static void lib_link_customdata_mtface(FileData *fd, Mesh *me, CustomData *fdata, int totface)
03617 {
03618     int i;  
03619     for(i=0; i<fdata->totlayer; i++) {
03620         CustomDataLayer *layer = &fdata->layers[i];
03621         
03622         if(layer->type == CD_MTFACE)
03623             lib_link_mtface(fd, me, layer->data, totface);
03624     }
03625 
03626 }
03627 
03628 static void lib_link_mesh(FileData *fd, Main *main)
03629 {
03630     Mesh *me;
03631 
03632     me= main->mesh.first;
03633     while(me) {
03634         if(me->id.flag & LIB_NEEDLINK) {
03635             int i;
03636 
03637             /*Link ID Properties -- and copy this comment EXACTLY for easy finding
03638             of library blocks that implement this.*/
03639             if (me->id.properties) IDP_LibLinkProperty(me->id.properties, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
03640             if (me->adt) lib_link_animdata(fd, &me->id, me->adt);
03641 
03642             /* this check added for python created meshes */
03643             if(me->mat) {
03644                 for(i=0; i<me->totcol; i++) {
03645                     me->mat[i]= newlibadr_us(fd, me->id.lib, me->mat[i]);
03646                 }
03647             }
03648             else me->totcol= 0;
03649 
03650             me->ipo= newlibadr_us(fd, me->id.lib, me->ipo);
03651             me->key= newlibadr_us(fd, me->id.lib, me->key);
03652             me->texcomesh= newlibadr_us(fd, me->id.lib, me->texcomesh);
03653 
03654             lib_link_customdata_mtface(fd, me, &me->fdata, me->totface);
03655             if(me->mr && me->mr->levels.first)
03656                 lib_link_customdata_mtface(fd, me, &me->mr->fdata,
03657                                ((MultiresLevel*)me->mr->levels.first)->totface);
03658 
03659             me->id.flag -= LIB_NEEDLINK;
03660         }
03661         me= me->id.next;
03662     }
03663 
03664     /* convert texface options to material */
03665     convert_tface_mt(fd, main);
03666 }
03667 
03668 static void direct_link_dverts(FileData *fd, int count, MDeformVert *mdverts)
03669 {
03670     int i;
03671 
03672     if (mdverts == NULL) {
03673         return;
03674     }
03675 
03676     for (i= count; i > 0; i--, mdverts++) {
03677         if(mdverts->dw) {
03678             mdverts->dw= newdataadr(fd, mdverts->dw);
03679         }
03680         if (mdverts->dw == NULL) {
03681             mdverts->totweight= 0;
03682         }
03683     }
03684 }
03685 
03686 static void direct_link_mdisps(FileData *fd, int count, MDisps *mdisps, int external)
03687 {
03688     if(mdisps) {
03689         int i;
03690 
03691         for(i = 0; i < count; ++i) {
03692             mdisps[i].disps = newdataadr(fd, mdisps[i].disps);
03693 
03694             if( (fd->flags & FD_FLAGS_SWITCH_ENDIAN) && (mdisps[i].disps) ) {
03695                 /* DNA_struct_switch_endian doesn't do endian swap for (*disps)[] */
03696                 /* this does swap for data written at write_mdisps() - readfile.c */
03697                 int x;
03698                 float *tmpdisps= *mdisps[i].disps;
03699                 for(x=0;x<mdisps[i].totdisp*3;x++) {
03700                     SWITCH_INT(*tmpdisps);
03701                     tmpdisps++;
03702                 }
03703             }
03704             if(!external && !mdisps[i].disps)
03705                 mdisps[i].totdisp = 0;
03706         }
03707     }
03708 }
03709 
03710 /*this isn't really a public api function, so prototyped here*/
03711 static void direct_link_customdata(FileData *fd, CustomData *data, int count)
03712 {
03713     int i = 0;
03714 
03715     data->layers= newdataadr(fd, data->layers);
03716     data->external= newdataadr(fd, data->external);
03717 
03718     while (i < data->totlayer) {
03719         CustomDataLayer *layer = &data->layers[i];
03720 
03721         if(layer->flag & CD_FLAG_EXTERNAL)
03722             layer->flag &= ~CD_FLAG_IN_MEMORY;
03723 
03724         if (CustomData_verify_versions(data, i)) {
03725             layer->data = newdataadr(fd, layer->data);
03726             if(layer->type == CD_MDISPS)
03727                 direct_link_mdisps(fd, count, layer->data, layer->flag & CD_FLAG_EXTERNAL);
03728             i++;
03729         }
03730     }
03731 
03732     CustomData_update_typemap(data);
03733 }
03734 
03735 static void direct_link_mesh(FileData *fd, Mesh *mesh)
03736 {
03737     mesh->mat= newdataadr(fd, mesh->mat);
03738     test_pointer_array(fd, (void **)&mesh->mat);
03739 
03740     mesh->mvert= newdataadr(fd, mesh->mvert);
03741     mesh->medge= newdataadr(fd, mesh->medge);
03742     mesh->mface= newdataadr(fd, mesh->mface);
03743     mesh->tface= newdataadr(fd, mesh->tface);
03744     mesh->mtface= newdataadr(fd, mesh->mtface);
03745     mesh->mcol= newdataadr(fd, mesh->mcol);
03746     mesh->msticky= newdataadr(fd, mesh->msticky);
03747     mesh->dvert= newdataadr(fd, mesh->dvert);
03748     
03749     /* animdata */
03750     mesh->adt= newdataadr(fd, mesh->adt);
03751     direct_link_animdata(fd, mesh->adt);
03752 
03753     /* normally direct_link_dverts should be called in direct_link_customdata,
03754        but for backwards compat in do_versions to work we do it here */
03755     direct_link_dverts(fd, mesh->totvert, mesh->dvert);
03756 
03757     direct_link_customdata(fd, &mesh->vdata, mesh->totvert);
03758     direct_link_customdata(fd, &mesh->edata, mesh->totedge);
03759     direct_link_customdata(fd, &mesh->fdata, mesh->totface);
03760 
03761 
03762 #ifdef USE_BMESH_FORWARD_COMPAT
03763     /* NEVER ENABLE THIS CODE INTO BMESH!
03764      * THIS IS FOR LOADING BMESH INTO OLDER FILES ONLY */
03765     mesh->mpoly= newdataadr(fd, mesh->mpoly);
03766     mesh->mloop= newdataadr(fd, mesh->mloop);
03767 
03768     direct_link_customdata(fd, &mesh->pdata, mesh->totpoly);
03769     direct_link_customdata(fd, &mesh->ldata, mesh->totloop);
03770 
03771     if (mesh->mpoly) {
03772         /* be clever and load polygons as mfaces */
03773 
03774         mesh->totface= mesh_mpoly_to_mface(&mesh->fdata, &mesh->ldata, &mesh->pdata,
03775                                            mesh->totface, mesh->totloop, mesh->totpoly);
03776 
03777         CustomData_free(&mesh->pdata, mesh->totpoly);
03778         memset(&mesh->pdata, 0, sizeof(CustomData));
03779         mesh->totpoly = 0;
03780 
03781         CustomData_free(&mesh->ldata, mesh->totloop);
03782         memset(&mesh->ldata, 0, sizeof(CustomData));
03783         mesh->totloop = 0;
03784 
03785         mesh_update_customdata_pointers(mesh);
03786     }
03787 
03788 #endif
03789 
03790 
03791     mesh->bb= NULL;
03792     mesh->mselect = NULL;
03793     mesh->edit_mesh= NULL;
03794     
03795     /* Multires data */
03796     mesh->mr= newdataadr(fd, mesh->mr);
03797     if(mesh->mr) {
03798         MultiresLevel *lvl;
03799         
03800         link_list(fd, &mesh->mr->levels);
03801         lvl= mesh->mr->levels.first;
03802         
03803         direct_link_customdata(fd, &mesh->mr->vdata, lvl->totvert);
03804         direct_link_dverts(fd, lvl->totvert, CustomData_get(&mesh->mr->vdata, 0, CD_MDEFORMVERT));
03805         direct_link_customdata(fd, &mesh->mr->fdata, lvl->totface);
03806         
03807         mesh->mr->edge_flags= newdataadr(fd, mesh->mr->edge_flags);
03808         mesh->mr->edge_creases= newdataadr(fd, mesh->mr->edge_creases);
03809 
03810         mesh->mr->verts = newdataadr(fd, mesh->mr->verts);
03811         
03812         /* If mesh has the same number of vertices as the
03813            highest multires level, load the current mesh verts
03814            into multires and discard the old data. Needed
03815            because some saved files either do not have a verts
03816            array, or the verts array contains out-of-date
03817            data. */
03818         if(mesh->totvert == ((MultiresLevel*)mesh->mr->levels.last)->totvert) {
03819             if(mesh->mr->verts)
03820                 MEM_freeN(mesh->mr->verts);
03821             mesh->mr->verts = MEM_dupallocN(mesh->mvert);
03822         }
03823             
03824         for(; lvl; lvl= lvl->next) {
03825             lvl->verts= newdataadr(fd, lvl->verts);
03826             lvl->faces= newdataadr(fd, lvl->faces);
03827             lvl->edges= newdataadr(fd, lvl->edges);
03828             lvl->colfaces= newdataadr(fd, lvl->colfaces);
03829         }
03830     }
03831 
03832     /* if multires is present but has no valid vertex data,
03833      * there's no way to recover it; silently remove multires */
03834     if(mesh->mr && !mesh->mr->verts) {
03835         multires_free(mesh->mr);
03836         mesh->mr = NULL;
03837     }
03838     
03839     if((fd->flags & FD_FLAGS_SWITCH_ENDIAN) && mesh->tface) {
03840         TFace *tf= mesh->tface;
03841         unsigned int i;
03842 
03843         for (i=0; i< (mesh->totface); i++, tf++) {
03844             SWITCH_INT(tf->col[0]);
03845             SWITCH_INT(tf->col[1]);
03846             SWITCH_INT(tf->col[2]);
03847             SWITCH_INT(tf->col[3]);
03848         }
03849     }
03850 }
03851 
03852 /* ************ READ LATTICE ***************** */
03853 
03854 static void lib_link_latt(FileData *fd, Main *main)
03855 {
03856     Lattice *lt;
03857     
03858     lt= main->latt.first;
03859     while(lt) {
03860         if(lt->id.flag & LIB_NEEDLINK) {
03861             if(lt->adt) lib_link_animdata(fd, &lt->id, lt->adt);
03862             
03863             lt->ipo= newlibadr_us(fd, lt->id.lib, lt->ipo); // XXX depreceated - old animation system
03864             lt->key= newlibadr_us(fd, lt->id.lib, lt->key);
03865             
03866             lt->id.flag -= LIB_NEEDLINK;
03867         }
03868         lt= lt->id.next;
03869     }
03870 }
03871 
03872 static void direct_link_latt(FileData *fd, Lattice *lt)
03873 {
03874     lt->def= newdataadr(fd, lt->def);
03875     
03876     lt->dvert= newdataadr(fd, lt->dvert);
03877     direct_link_dverts(fd, lt->pntsu*lt->pntsv*lt->pntsw, lt->dvert);
03878     
03879     lt->editlatt= NULL;
03880     
03881     lt->adt = newdataadr(fd, lt->adt);
03882     direct_link_animdata(fd, lt->adt);
03883 }
03884 
03885 
03886 /* ************ READ OBJECT ***************** */
03887 
03888 static void lib_link_modifiers__linkModifiers(void *userData, Object *ob,
03889                                               ID **idpoin)
03890 {
03891     FileData *fd = userData;
03892 
03893     *idpoin = newlibadr(fd, ob->id.lib, *idpoin);
03894     /* hardcoded bad exception; non-object modifier data gets user count (texture, displace) */
03895     if(*idpoin && GS((*idpoin)->name)!=ID_OB)
03896         (*idpoin)->us++;
03897 }
03898 static void lib_link_modifiers(FileData *fd, Object *ob)
03899 {
03900     modifiers_foreachIDLink(ob, lib_link_modifiers__linkModifiers, fd);
03901 }
03902 
03903 static void lib_link_object(FileData *fd, Main *main)
03904 {
03905     Object *ob;
03906     PartEff *paf;
03907     bSensor *sens;
03908     bController *cont;
03909     bActuator *act;
03910     void *poin;
03911     int warn=0, a;
03912 
03913     ob= main->object.first;
03914     while(ob) {
03915         if(ob->id.flag & LIB_NEEDLINK) {
03916             if (ob->id.properties) IDP_LibLinkProperty(ob->id.properties, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
03917             if (ob->adt) lib_link_animdata(fd, &ob->id, ob->adt);
03918             
03919 // XXX depreceated - old animation system <<<           
03920             ob->ipo= newlibadr_us(fd, ob->id.lib, ob->ipo);
03921             ob->action = newlibadr_us(fd, ob->id.lib, ob->action);
03922 // >>> XXX depreceated - old animation system
03923 
03924             ob->parent= newlibadr(fd, ob->id.lib, ob->parent);
03925             ob->track= newlibadr(fd, ob->id.lib, ob->track);
03926             ob->poselib= newlibadr_us(fd, ob->id.lib, ob->poselib);
03927             ob->dup_group= newlibadr_us(fd, ob->id.lib, ob->dup_group);
03928             
03929             ob->proxy= newlibadr_us(fd, ob->id.lib, ob->proxy);
03930             if(ob->proxy) {
03931                 /* paranoia check, actually a proxy_from pointer should never be written... */
03932                 if(ob->proxy->id.lib==NULL) {
03933                     ob->proxy->proxy_from= NULL;
03934                     ob->proxy= NULL;
03935                     
03936                     if (ob->id.lib)
03937                         printf("Proxy lost from  object %s lib %s\n", ob->id.name+2, ob->id.lib->name);
03938                     else
03939                         printf("Proxy lost from  object %s lib <NONE>\n", ob->id.name+2);
03940                 }
03941                 else {
03942                     /* this triggers object_update to always use a copy */
03943                     ob->proxy->proxy_from= ob;
03944                     /* force proxy updates after load/undo, a bit weak */
03945                     ob->recalc= ob->proxy->recalc= OB_RECALC_OB|OB_RECALC_DATA|OB_RECALC_TIME;
03946                 }
03947             }
03948             ob->proxy_group= newlibadr(fd, ob->id.lib, ob->proxy_group);
03949             
03950             poin= ob->data;
03951             ob->data= newlibadr_us(fd, ob->id.lib, ob->data);
03952 
03953             if(ob->data==NULL && poin!=NULL) {
03954                 if(ob->id.lib)
03955                     printf("Can't find obdata of %s lib %s\n", ob->id.name+2, ob->id.lib->name);
03956                 else
03957                     printf("Object %s lost data.\n", ob->id.name+2);
03958 
03959                 ob->type= OB_EMPTY;
03960                 warn= 1;
03961 
03962                 if(ob->pose) {
03963                     free_pose(ob->pose);
03964                     ob->pose= NULL;
03965                     ob->mode &= ~OB_MODE_POSE;
03966                 }
03967             }
03968             for(a=0; a<ob->totcol; a++) ob->mat[a]= newlibadr_us(fd, ob->id.lib, ob->mat[a]);
03969             
03970             /* When the object is local and the data is library its possible
03971              * the material list size gets out of sync. [#22663] */
03972             if(ob->data && ob->id.lib != ((ID *)ob->data)->lib) {
03973                 short *totcol_data= give_totcolp(ob);
03974                 /* Only expand so as not to loose any object materials that might be set. */
03975                 if(totcol_data && *totcol_data > ob->totcol) {
03976                     /* printf("'%s' %d -> %d\n", ob->id.name, ob->totcol, *totcol_data); */
03977                     resize_object_material(ob, *totcol_data);
03978                 }
03979             }
03980 
03981             ob->gpd= newlibadr_us(fd, ob->id.lib, ob->gpd);
03982             ob->duplilist= NULL;
03983 
03984             ob->id.flag -= LIB_NEEDLINK;
03985             /* if id.us==0 a new base will be created later on */
03986             
03987             /* WARNING! Also check expand_object(), should reflect the stuff below. */
03988             lib_link_pose(fd, ob, ob->pose);
03989             lib_link_constraints(fd, &ob->id, &ob->constraints);
03990             
03991 // XXX depreceated - old animation system <<<   
03992             lib_link_constraint_channels(fd, &ob->id, &ob->constraintChannels);
03993             lib_link_nlastrips(fd, &ob->id, &ob->nlastrips);
03994 // >>> XXX depreceated - old animation system
03995 
03996             for(paf= ob->effect.first; paf; paf= paf->next) {
03997                 if(paf->type==EFF_PARTICLE) {
03998                     paf->group= newlibadr_us(fd, ob->id.lib, paf->group);
03999                 }
04000             }               
04001 
04002             sens= ob->sensors.first;
04003             while(sens) {
04004                 for(a=0; a<sens->totlinks; a++)
04005                     sens->links[a]= newglobadr(fd, sens->links[a]);
04006 
04007                 if(sens->type==SENS_TOUCH) {
04008                     bTouchSensor *ts= sens->data;
04009                     ts->ma= newlibadr(fd, ob->id.lib, ts->ma);
04010                 }
04011                 else if(sens->type==SENS_MESSAGE) {
04012                     bMessageSensor *ms= sens->data;
04013                     ms->fromObject=
04014                         newlibadr(fd, ob->id.lib, ms->fromObject);
04015                 }
04016                 sens= sens->next;
04017             }
04018 
04019             cont= ob->controllers.first;
04020             while(cont) {
04021                 for(a=0; a<cont->totlinks; a++)
04022                     cont->links[a]= newglobadr(fd, cont->links[a]);
04023 
04024                 if(cont->type==CONT_PYTHON) {
04025                     bPythonCont *pc= cont->data;
04026                     pc->text= newlibadr(fd, ob->id.lib, pc->text);
04027                 }
04028                 cont->slinks= NULL;
04029                 cont->totslinks= 0;
04030 
04031                 cont= cont->next;
04032             }
04033 
04034             act= ob->actuators.first;
04035             while(act) {
04036                 if(act->type==ACT_SOUND) {
04037                     bSoundActuator *sa= act->data;
04038                     sa->sound= newlibadr_us(fd, ob->id.lib, sa->sound);
04039                 }
04040                 else if(act->type==ACT_GAME) {
04041                     /* bGameActuator *ga= act->data; */
04042                 }
04043                 else if(act->type==ACT_CAMERA) {
04044                     bCameraActuator *ca= act->data;
04045                     ca->ob= newlibadr(fd, ob->id.lib, ca->ob);
04046                 }
04047                     /* leave this one, it's obsolete but necessary to read for conversion */
04048                 else if(act->type==ACT_ADD_OBJECT) {
04049                     bAddObjectActuator *eoa= act->data;
04050                     if(eoa) eoa->ob= newlibadr(fd, ob->id.lib, eoa->ob);
04051                 }
04052                 else if(act->type==ACT_OBJECT) {
04053                     bObjectActuator *oa= act->data;
04054                     if(oa==NULL) {
04055                         init_actuator(act);
04056                     }
04057                     else {
04058                         oa->reference= newlibadr(fd, ob->id.lib, oa->reference);
04059                     }
04060                 }
04061                 else if(act->type==ACT_EDIT_OBJECT) {
04062                     bEditObjectActuator *eoa= act->data;
04063                     if(eoa==NULL) {
04064                         init_actuator(act);
04065                     }
04066                     else {
04067                         eoa->ob= newlibadr(fd, ob->id.lib, eoa->ob);
04068                         eoa->me= newlibadr(fd, ob->id.lib, eoa->me);
04069                     }
04070                 }
04071                 else if(act->type==ACT_SCENE) {
04072                     bSceneActuator *sa= act->data;
04073                     sa->camera= newlibadr(fd, ob->id.lib, sa->camera);
04074                     sa->scene= newlibadr(fd, ob->id.lib, sa->scene);
04075                 }
04076                 else if(act->type==ACT_ACTION) {
04077                     bActionActuator *aa= act->data;
04078                     aa->act= newlibadr(fd, ob->id.lib, aa->act);
04079                 }
04080                 else if(act->type==ACT_SHAPEACTION) {
04081                     bActionActuator *aa= act->data;
04082                     aa->act= newlibadr(fd, ob->id.lib, aa->act);
04083                 }
04084                 else if(act->type==ACT_PROPERTY) {
04085                     bPropertyActuator *pa= act->data;
04086                     pa->ob= newlibadr(fd, ob->id.lib, pa->ob);
04087                 }
04088                 else if(act->type==ACT_MESSAGE) {
04089                     bMessageActuator *ma= act->data;
04090                     ma->toObject= newlibadr(fd, ob->id.lib, ma->toObject);
04091                 }
04092                 else if(act->type==ACT_2DFILTER){
04093                     bTwoDFilterActuator *_2dfa = act->data; 
04094                     _2dfa->text= newlibadr(fd, ob->id.lib, _2dfa->text);
04095                 }
04096                 else if(act->type==ACT_PARENT) {
04097                     bParentActuator *parenta = act->data; 
04098                     parenta->ob = newlibadr(fd, ob->id.lib, parenta->ob);
04099                 }
04100                 else if(act->type==ACT_STATE) {
04101                     /* bStateActuator *statea = act->data; */
04102                 }
04103                 else if(act->type==ACT_ARMATURE) {
04104                     bArmatureActuator *arma= act->data;
04105                     arma->target= newlibadr(fd, ob->id.lib, arma->target);
04106                     arma->subtarget= newlibadr(fd, ob->id.lib, arma->subtarget);
04107                 }
04108                 else if(act->type==ACT_STEERING) {
04109                     bSteeringActuator *steeringa = act->data; 
04110                     steeringa->target = newlibadr(fd, ob->id.lib, steeringa->target);
04111                     steeringa->navmesh = newlibadr(fd, ob->id.lib, steeringa->navmesh);
04112                 }
04113                 act= act->next;
04114             }
04115             
04116             {
04117                 FluidsimModifierData *fluidmd = (FluidsimModifierData *)modifiers_findByType(ob, eModifierType_Fluidsim);
04118                 
04119                 if(fluidmd && fluidmd->fss) 
04120                     fluidmd->fss->ipo = newlibadr_us(fd, ob->id.lib, fluidmd->fss->ipo);
04121             }
04122 
04123             {
04124                 SmokeModifierData *smd = (SmokeModifierData *)modifiers_findByType(ob, eModifierType_Smoke);
04125                 
04126                 if(smd && smd->type == MOD_SMOKE_TYPE_DOMAIN && smd->domain) 
04127                 {
04128                     smd->domain->flags |= MOD_SMOKE_FILE_LOAD; /* flag for refreshing the simulation after loading */
04129                 }
04130             }
04131 
04132             /* texture field */
04133             if(ob->pd)
04134                 lib_link_partdeflect(fd, &ob->id, ob->pd);
04135 
04136             if(ob->soft)
04137                 ob->soft->effector_weights->group = newlibadr(fd, ob->id.lib, ob->soft->effector_weights->group);
04138 
04139             lib_link_particlesystems(fd, ob, &ob->id, &ob->particlesystem);
04140             lib_link_modifiers(fd, ob);
04141         }
04142         ob= ob->id.next;
04143     }
04144 
04145     if(warn) {
04146         BKE_report(fd->reports, RPT_WARNING, "Warning in console");
04147     }
04148 }
04149 
04150 
04151 static void direct_link_pose(FileData *fd, bPose *pose)
04152 {
04153     bPoseChannel *pchan;
04154 
04155     if (!pose)
04156         return;
04157 
04158     link_list(fd, &pose->chanbase);
04159     link_list(fd, &pose->agroups);
04160 
04161     pose->chanhash= NULL;
04162 
04163     for (pchan = pose->chanbase.first; pchan; pchan=pchan->next) {
04164         pchan->bone= NULL;
04165         pchan->parent= newdataadr(fd, pchan->parent);
04166         pchan->child= newdataadr(fd, pchan->child);
04167         pchan->custom_tx= newdataadr(fd, pchan->custom_tx);
04168         
04169         direct_link_constraints(fd, &pchan->constraints);
04170         
04171         pchan->prop = newdataadr(fd, pchan->prop);
04172         if (pchan->prop)
04173             IDP_DirectLinkProperty(pchan->prop, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
04174         
04175         pchan->mpath= newdataadr(fd, pchan->mpath);
04176         if (pchan->mpath)
04177             direct_link_motionpath(fd, pchan->mpath);
04178         
04179         pchan->iktree.first= pchan->iktree.last= NULL;
04180         pchan->siktree.first= pchan->siktree.last= NULL;
04181         
04182         /* incase this value changes in future, clamp else we get undefined behavior */
04183         CLAMP(pchan->rotmode, ROT_MODE_MIN, ROT_MODE_MAX);
04184     }
04185     pose->ikdata = NULL;
04186     if (pose->ikparam != NULL) {
04187         pose->ikparam= newdataadr(fd, pose->ikparam);
04188     }
04189 }
04190 
04191 static void direct_link_modifiers(FileData *fd, ListBase *lb)
04192 {
04193     ModifierData *md;
04194 
04195     link_list(fd, lb);
04196 
04197     for (md=lb->first; md; md=md->next) {
04198         md->error = NULL;
04199         md->scene = NULL;
04200         
04201         /* if modifiers disappear, or for upward compatibility */
04202         if(NULL==modifierType_getInfo(md->type))
04203             md->type= eModifierType_None;
04204             
04205         if (md->type==eModifierType_Subsurf) {
04206             SubsurfModifierData *smd = (SubsurfModifierData*) md;
04207 
04208             smd->emCache = smd->mCache = NULL;
04209         }
04210         else if (md->type==eModifierType_Armature) {
04211             ArmatureModifierData *amd = (ArmatureModifierData*) md;
04212             
04213             amd->prevCos= NULL;
04214         }
04215         else if (md->type==eModifierType_Cloth) {
04216             ClothModifierData *clmd = (ClothModifierData*) md;
04217             
04218             clmd->clothObject = NULL;
04219             
04220             clmd->sim_parms= newdataadr(fd, clmd->sim_parms);
04221             clmd->coll_parms= newdataadr(fd, clmd->coll_parms);
04222 
04223             direct_link_pointcache_list(fd, &clmd->ptcaches, &clmd->point_cache, 0);
04224             
04225             if(clmd->sim_parms) {
04226                 if(clmd->sim_parms->presets > 10)
04227                     clmd->sim_parms->presets = 0;
04228 
04229                 clmd->sim_parms->reset = 0;
04230 
04231                 clmd->sim_parms->effector_weights = newdataadr(fd, clmd->sim_parms->effector_weights);
04232 
04233                 if(!clmd->sim_parms->effector_weights) {
04234                     clmd->sim_parms->effector_weights = BKE_add_effector_weights(NULL);
04235                 }
04236             }
04237         }
04238         else if (md->type==eModifierType_Fluidsim) {
04239             FluidsimModifierData *fluidmd = (FluidsimModifierData*) md;
04240             
04241             fluidmd->fss= newdataadr(fd, fluidmd->fss);
04242             if(fluidmd->fss) {
04243                 fluidmd->fss->fmd= fluidmd;
04244                 fluidmd->fss->meshVelocities = NULL;
04245             }
04246         }
04247         else if (md->type==eModifierType_Smoke) {
04248             SmokeModifierData *smd = (SmokeModifierData*) md;
04249 
04250             if(smd->type==MOD_SMOKE_TYPE_DOMAIN)
04251             {
04252                 smd->flow = NULL;
04253                 smd->coll = NULL;
04254                 smd->domain = newdataadr(fd, smd->domain);
04255                 smd->domain->smd = smd;
04256 
04257                 smd->domain->fluid = NULL;
04258                 smd->domain->wt = NULL;
04259                 smd->domain->shadow = NULL;
04260                 smd->domain->tex = NULL;
04261                 smd->domain->tex_shadow = NULL;
04262                 smd->domain->tex_wt = NULL;
04263 
04264                 smd->domain->effector_weights = newdataadr(fd, smd->domain->effector_weights);
04265                 if(!smd->domain->effector_weights)
04266                     smd->domain->effector_weights = BKE_add_effector_weights(NULL);
04267 
04268                 direct_link_pointcache_list(fd, &(smd->domain->ptcaches[0]), &(smd->domain->point_cache[0]), 1);
04269 
04270                 /* Smoke uses only one cache from now on, so store pointer convert */
04271                 if(smd->domain->ptcaches[1].first || smd->domain->point_cache[1]) {
04272                     if(smd->domain->point_cache[1]) {
04273                         PointCache *cache = newdataadr(fd, smd->domain->point_cache[1]);
04274                         if(cache->flag & PTCACHE_FAKE_SMOKE)
04275                             ; /* Smoke was already saved in "new format" and this cache is a fake one. */
04276                         else
04277                             printf("High resolution smoke cache not available due to pointcache update. Please reset the simulation.\n");
04278                         BKE_ptcache_free(cache);
04279                     }
04280                     smd->domain->ptcaches[1].first = NULL;
04281                     smd->domain->ptcaches[1].last = NULL;
04282                     smd->domain->point_cache[1] = NULL;
04283                 }
04284             }
04285             else if(smd->type==MOD_SMOKE_TYPE_FLOW)
04286             {
04287                 smd->domain = NULL;
04288                 smd->coll = NULL;
04289                 smd->flow = newdataadr(fd, smd->flow);
04290                 smd->flow->smd = smd;
04291                 smd->flow->psys = newdataadr(fd, smd->flow->psys);
04292             }
04293             else if(smd->type==MOD_SMOKE_TYPE_COLL)
04294             {
04295                 smd->flow = NULL;
04296                 smd->domain = NULL;
04297                 smd->coll = newdataadr(fd, smd->coll);
04298                 if(smd->coll)
04299                 {
04300                     smd->coll->points = NULL;
04301                     smd->coll->numpoints = 0;
04302                 }
04303                 else
04304                     smd->type = 0;
04305 
04306             }
04307         }
04308         else if (md->type==eModifierType_DynamicPaint) {
04309             DynamicPaintModifierData *pmd = (DynamicPaintModifierData*) md;
04310 
04311             if(pmd->canvas)
04312             {
04313                 pmd->canvas = newdataadr(fd, pmd->canvas);
04314                 pmd->canvas->pmd = pmd;
04315                 pmd->canvas->dm = NULL;
04316                 pmd->canvas->flags &= ~MOD_DPAINT_BAKING; /* just in case */
04317 
04318                 if (pmd->canvas->surfaces.first) {
04319                     DynamicPaintSurface *surface;
04320                     link_list(fd, &pmd->canvas->surfaces);
04321 
04322                     for (surface=pmd->canvas->surfaces.first; surface; surface=surface->next) {
04323                         surface->canvas = pmd->canvas;
04324                         surface->data = NULL;
04325                         direct_link_pointcache_list(fd, &(surface->ptcaches), &(surface->pointcache), 1);
04326 
04327                         if(!(surface->effector_weights = newdataadr(fd, surface->effector_weights)))
04328                             surface->effector_weights = BKE_add_effector_weights(NULL);
04329                     }
04330                 }
04331             }
04332             if(pmd->brush)
04333             {
04334                 pmd->brush = newdataadr(fd, pmd->brush);
04335                 pmd->brush->pmd = pmd;
04336                 pmd->brush->psys = newdataadr(fd, pmd->brush->psys);
04337                 pmd->brush->paint_ramp = newdataadr(fd, pmd->brush->paint_ramp);
04338                 pmd->brush->vel_ramp = newdataadr(fd, pmd->brush->vel_ramp);
04339                 pmd->brush->dm = NULL;
04340             }
04341         }
04342         else if (md->type==eModifierType_Collision) {
04343             
04344             CollisionModifierData *collmd = (CollisionModifierData*) md;
04345             /*
04346             // TODO: CollisionModifier should use pointcache 
04347             // + have proper reset events before enabling this
04348             collmd->x = newdataadr(fd, collmd->x);
04349             collmd->xnew = newdataadr(fd, collmd->xnew);
04350             collmd->mfaces = newdataadr(fd, collmd->mfaces);
04351             
04352             collmd->current_x = MEM_callocN(sizeof(MVert)*collmd->numverts,"current_x");
04353             collmd->current_xnew = MEM_callocN(sizeof(MVert)*collmd->numverts,"current_xnew");
04354             collmd->current_v = MEM_callocN(sizeof(MVert)*collmd->numverts,"current_v");
04355             */
04356             
04357             collmd->x = NULL;
04358             collmd->xnew = NULL;
04359             collmd->current_x = NULL;
04360             collmd->current_xnew = NULL;
04361             collmd->current_v = NULL;
04362             collmd->time_x = collmd->time_xnew = -1000;
04363             collmd->numverts = 0;
04364             collmd->bvhtree = NULL;
04365             collmd->mfaces = NULL;
04366             
04367         }
04368         else if (md->type==eModifierType_Surface) {
04369             SurfaceModifierData *surmd = (SurfaceModifierData*) md;
04370 
04371             surmd->dm = NULL;
04372             surmd->bvhtree = NULL;
04373             surmd->x = NULL;
04374             surmd->v = NULL;
04375             surmd->numverts = 0;
04376         }
04377         else if (md->type==eModifierType_Hook) {
04378             HookModifierData *hmd = (HookModifierData*) md;
04379 
04380             hmd->indexar= newdataadr(fd, hmd->indexar);
04381             if(fd->flags & FD_FLAGS_SWITCH_ENDIAN) {
04382                 int a;
04383                 for(a=0; a<hmd->totindex; a++) {
04384                     SWITCH_INT(hmd->indexar[a]);
04385                 }
04386             }
04387         } else if (md->type==eModifierType_ParticleSystem) {
04388             ParticleSystemModifierData *psmd = (ParticleSystemModifierData*) md;
04389 
04390             psmd->dm= NULL;
04391             psmd->psys= newdataadr(fd, psmd->psys);
04392             psmd->flag &= ~eParticleSystemFlag_psys_updated;
04393             psmd->flag |= eParticleSystemFlag_file_loaded;
04394         } else if (md->type==eModifierType_Explode) {
04395             ExplodeModifierData *psmd = (ExplodeModifierData*) md;
04396 
04397             psmd->facepa=NULL;
04398         }
04399         else if (md->type==eModifierType_MeshDeform) {
04400             MeshDeformModifierData *mmd = (MeshDeformModifierData*) md;
04401 
04402             mmd->bindinfluences= newdataadr(fd, mmd->bindinfluences);
04403             mmd->bindoffsets= newdataadr(fd, mmd->bindoffsets);
04404             mmd->bindcagecos= newdataadr(fd, mmd->bindcagecos);
04405             mmd->dyngrid= newdataadr(fd, mmd->dyngrid);
04406             mmd->dyninfluences= newdataadr(fd, mmd->dyninfluences);
04407             mmd->dynverts= newdataadr(fd, mmd->dynverts);
04408 
04409             mmd->bindweights= newdataadr(fd, mmd->bindweights);
04410             mmd->bindcos= newdataadr(fd, mmd->bindcos);
04411 
04412             if(fd->flags & FD_FLAGS_SWITCH_ENDIAN) {
04413                 int a;
04414 
04415                 if(mmd->bindoffsets)
04416                     for(a=0; a<mmd->totvert+1; a++)
04417                         SWITCH_INT(mmd->bindoffsets[a])
04418                 if(mmd->bindcagecos)
04419                     for(a=0; a<mmd->totcagevert*3; a++)
04420                         SWITCH_INT(mmd->bindcagecos[a])
04421                 if(mmd->dynverts)
04422                     for(a=0; a<mmd->totvert; a++)
04423                         SWITCH_INT(mmd->dynverts[a])
04424 
04425                 if(mmd->bindweights)
04426                     for(a=0; a<mmd->totcagevert*mmd->totvert; a++)
04427                         SWITCH_INT(mmd->bindweights[a])
04428                 if(mmd->bindcos)
04429                     for(a=0; a<mmd->totcagevert*3; a++)
04430                         SWITCH_INT(mmd->bindcos[a])
04431             }
04432         }
04433         else if (md->type==eModifierType_Ocean) {
04434             OceanModifierData *omd = (OceanModifierData*) md;
04435             omd->oceancache = NULL;
04436             omd->ocean = NULL;
04437             omd->refresh = (MOD_OCEAN_REFRESH_ADD|MOD_OCEAN_REFRESH_RESET|MOD_OCEAN_REFRESH_SIM);
04438         }
04439         else if (md->type==eModifierType_Warp) {
04440             WarpModifierData *tmd = (WarpModifierData *) md;
04441 
04442             tmd->curfalloff= newdataadr(fd, tmd->curfalloff);
04443             if(tmd->curfalloff)
04444                 direct_link_curvemapping(fd, tmd->curfalloff);
04445         }
04446         else if (md->type==eModifierType_WeightVGEdit) {
04447             WeightVGEditModifierData *wmd = (WeightVGEditModifierData*) md;
04448 
04449             wmd->cmap_curve = newdataadr(fd, wmd->cmap_curve);
04450             if(wmd->cmap_curve)
04451                 direct_link_curvemapping(fd, wmd->cmap_curve);
04452         }
04453     }
04454 }
04455 
04456 static void direct_link_object(FileData *fd, Object *ob)
04457 {
04458     PartEff *paf;
04459     bProperty *prop;
04460     bSensor *sens;
04461     bController *cont;
04462     bActuator *act;
04463     
04464     /* weak weak... this was only meant as draw flag, now is used in give_base_to_objects too */
04465     ob->flag &= ~OB_FROMGROUP;
04466 
04467     /* loading saved files with editmode enabled works, but for undo we like
04468        to stay in object mode during undo presses so keep editmode disabled */
04469     if(fd->memfile)
04470         ob->mode &= ~(OB_MODE_EDIT|OB_MODE_PARTICLE_EDIT);
04471     
04472     ob->disp.first=ob->disp.last= NULL;
04473     
04474     ob->adt= newdataadr(fd, ob->adt);
04475     direct_link_animdata(fd, ob->adt);
04476     
04477     ob->pose= newdataadr(fd, ob->pose);
04478     direct_link_pose(fd, ob->pose);
04479     
04480     ob->mpath= newdataadr(fd, ob->mpath);
04481     if (ob->mpath)
04482         direct_link_motionpath(fd, ob->mpath);
04483 
04484     link_list(fd, &ob->defbase);
04485 // XXX depreceated - old animation system <<<
04486     direct_link_nlastrips(fd, &ob->nlastrips);
04487     link_list(fd, &ob->constraintChannels);
04488 // >>> XXX depreceated - old animation system 
04489 
04490     ob->mat= newdataadr(fd, ob->mat);
04491     test_pointer_array(fd, (void **)&ob->mat);
04492     ob->matbits= newdataadr(fd, ob->matbits);
04493     
04494     /* do it here, below old data gets converted */
04495     direct_link_modifiers(fd, &ob->modifiers);
04496     
04497     link_list(fd, &ob->effect);
04498     paf= ob->effect.first;
04499     while(paf) {
04500         if(paf->type==EFF_PARTICLE) {
04501             paf->keys= NULL;
04502         }
04503         if(paf->type==EFF_WAVE) {
04504             WaveEff *wav = (WaveEff*) paf;
04505             PartEff *next = paf->next;
04506             WaveModifierData *wmd = (WaveModifierData*) modifier_new(eModifierType_Wave);
04507 
04508             wmd->damp = wav->damp;
04509             wmd->flag = wav->flag;
04510             wmd->height = wav->height;
04511             wmd->lifetime = wav->lifetime;
04512             wmd->narrow = wav->narrow;
04513             wmd->speed = wav->speed;
04514             wmd->startx = wav->startx;
04515             wmd->starty = wav->startx;
04516             wmd->timeoffs = wav->timeoffs;
04517             wmd->width = wav->width;
04518 
04519             BLI_addtail(&ob->modifiers, wmd);
04520 
04521             BLI_remlink(&ob->effect, paf);
04522             MEM_freeN(paf);
04523 
04524             paf = next;
04525             continue;
04526         }
04527         if(paf->type==EFF_BUILD) {
04528             BuildEff *baf = (BuildEff*) paf;
04529             PartEff *next = paf->next;
04530             BuildModifierData *bmd = (BuildModifierData*) modifier_new(eModifierType_Build);
04531 
04532             bmd->start = baf->sfra;
04533             bmd->length = baf->len;
04534             bmd->randomize = 0;
04535             bmd->seed = 1;
04536 
04537             BLI_addtail(&ob->modifiers, bmd);
04538 
04539             BLI_remlink(&ob->effect, paf);
04540             MEM_freeN(paf);
04541 
04542             paf = next;
04543             continue;
04544         }
04545         paf= paf->next;
04546     }
04547 
04548     ob->pd= newdataadr(fd, ob->pd);
04549     direct_link_partdeflect(ob->pd);
04550     ob->soft= newdataadr(fd, ob->soft);
04551     if(ob->soft) {
04552         SoftBody *sb= ob->soft;     
04553         
04554         sb->bpoint= NULL;   // init pointers so it gets rebuilt nicely
04555         sb->bspring= NULL;
04556         sb->scratch= NULL;
04557         /* although not used anymore */
04558         /* still have to be loaded to be compatible with old files */
04559         sb->keys= newdataadr(fd, sb->keys);
04560         test_pointer_array(fd, (void **)&sb->keys);
04561         if(sb->keys) {
04562             int a;
04563             for(a=0; a<sb->totkey; a++) {
04564                 sb->keys[a]= newdataadr(fd, sb->keys[a]);
04565             }
04566         }
04567 
04568         sb->effector_weights = newdataadr(fd, sb->effector_weights);
04569         if(!sb->effector_weights)
04570             sb->effector_weights = BKE_add_effector_weights(NULL);
04571 
04572         direct_link_pointcache_list(fd, &sb->ptcaches, &sb->pointcache, 0);
04573     }
04574     ob->bsoft= newdataadr(fd, ob->bsoft);
04575     ob->fluidsimSettings= newdataadr(fd, ob->fluidsimSettings); /* NT */
04576 
04577     link_list(fd, &ob->particlesystem);
04578     direct_link_particlesystems(fd,&ob->particlesystem);
04579     
04580     link_list(fd, &ob->prop);
04581     prop= ob->prop.first;
04582     while(prop) {
04583         prop->poin= newdataadr(fd, prop->poin);
04584         if(prop->poin==NULL) prop->poin= &prop->data;
04585         prop= prop->next;
04586     }
04587 
04588     link_list(fd, &ob->sensors);
04589     sens= ob->sensors.first;
04590     while(sens) {
04591         sens->data= newdataadr(fd, sens->data);
04592         sens->links= newdataadr(fd, sens->links);
04593         test_pointer_array(fd, (void **)&sens->links);
04594         sens= sens->next;
04595     }
04596 
04597     direct_link_constraints(fd, &ob->constraints);
04598 
04599     link_glob_list(fd, &ob->controllers);
04600     if (ob->init_state) {
04601         /* if a known first state is specified, set it so that the game will start ok */
04602         ob->state = ob->init_state;
04603     } else if (!ob->state) {
04604         ob->state = 1;
04605     }
04606     cont= ob->controllers.first;
04607     while(cont) {
04608         cont->data= newdataadr(fd, cont->data);
04609         cont->links= newdataadr(fd, cont->links);
04610         test_pointer_array(fd, (void **)&cont->links);
04611         if (cont->state_mask == 0)
04612             cont->state_mask = 1;
04613         cont= cont->next;
04614     }
04615 
04616     link_glob_list(fd, &ob->actuators);
04617     act= ob->actuators.first;
04618     while(act) {
04619         act->data= newdataadr(fd, act->data);
04620         act= act->next;
04621     }
04622 
04623     link_list(fd, &ob->hooks);
04624     while (ob->hooks.first) {
04625         ObHook *hook = ob->hooks.first;
04626         HookModifierData *hmd = (HookModifierData*) modifier_new(eModifierType_Hook);
04627 
04628         hook->indexar= newdataadr(fd, hook->indexar);
04629         if(fd->flags & FD_FLAGS_SWITCH_ENDIAN) {
04630             int a;
04631             for(a=0; a<hook->totindex; a++) {
04632                 SWITCH_INT(hook->indexar[a]);
04633             }
04634         }
04635 
04636             /* Do conversion here because if we have loaded
04637              * a hook we need to make sure it gets converted
04638              * and free'd, regardless of version.
04639              */
04640         copy_v3_v3(hmd->cent, hook->cent);
04641         hmd->falloff = hook->falloff;
04642         hmd->force = hook->force;
04643         hmd->indexar = hook->indexar;
04644         hmd->object = hook->parent;
04645         memcpy(hmd->parentinv, hook->parentinv, sizeof(hmd->parentinv));
04646         hmd->totindex = hook->totindex;
04647 
04648         BLI_addhead(&ob->modifiers, hmd);
04649         BLI_remlink(&ob->hooks, hook);
04650         
04651         modifier_unique_name(&ob->modifiers, (ModifierData*)hmd);
04652 
04653         MEM_freeN(hook);
04654     }
04655     
04656     ob->customdata_mask= 0;
04657     ob->bb= NULL;
04658     ob->derivedDeform= NULL;
04659     ob->derivedFinal= NULL;
04660     ob->gpulamp.first= ob->gpulamp.last= NULL;
04661     link_list(fd, &ob->pc_ids);
04662 
04663     /* incase this value changes in future, clamp else we get undefined behavior */
04664     CLAMP(ob->rotmode, ROT_MODE_MIN, ROT_MODE_MAX);
04665 
04666     if(ob->sculpt) {
04667         ob->sculpt= MEM_callocN(sizeof(SculptSession), "reload sculpt session");
04668     }
04669 }
04670 
04671 /* ************ READ SCENE ***************** */
04672 
04673 /* patch for missing scene IDs, can't be in do-versions */
04674 static void composite_patch(bNodeTree *ntree, Scene *scene)
04675 {
04676     bNode *node;
04677     
04678     for(node= ntree->nodes.first; node; node= node->next)
04679         if(node->id==NULL && ELEM4(node->type, CMP_NODE_R_LAYERS, CMP_NODE_COMPOSITE, CMP_NODE_DEFOCUS, CMP_NODE_OUTPUT_FILE))
04680             node->id= &scene->id;
04681 }
04682 
04683 static void link_paint(FileData *fd, Scene *sce, Paint *p)
04684 {
04685     if(p) {
04686         p->brush= newlibadr_us(fd, sce->id.lib, p->brush);
04687         p->paint_cursor= NULL;
04688     }
04689 }
04690 
04691 static void lib_link_scene(FileData *fd, Main *main)
04692 {
04693     Scene *sce;
04694     Base *base, *next;
04695     Sequence *seq;
04696     SceneRenderLayer *srl;
04697     TimeMarker *marker;
04698     
04699     sce= main->scene.first;
04700     while(sce) {
04701         if(sce->id.flag & LIB_NEEDLINK) {
04702             /*Link ID Properties -- and copy this comment EXACTLY for easy finding
04703             of library blocks that implement this.*/
04704             if (sce->id.properties) IDP_LibLinkProperty(sce->id.properties, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
04705             if (sce->adt) lib_link_animdata(fd, &sce->id, sce->adt);
04706             
04707             lib_link_keyingsets(fd, &sce->id, &sce->keyingsets);
04708             
04709             sce->camera= newlibadr(fd, sce->id.lib, sce->camera);
04710             sce->world= newlibadr_us(fd, sce->id.lib, sce->world);
04711             sce->set= newlibadr(fd, sce->id.lib, sce->set);
04712             sce->gpd= newlibadr_us(fd, sce->id.lib, sce->gpd);
04713             
04714             link_paint(fd, sce, &sce->toolsettings->sculpt->paint);
04715             link_paint(fd, sce, &sce->toolsettings->vpaint->paint);
04716             link_paint(fd, sce, &sce->toolsettings->wpaint->paint);
04717             link_paint(fd, sce, &sce->toolsettings->imapaint.paint);
04718 
04719             sce->toolsettings->skgen_template = newlibadr(fd, sce->id.lib, sce->toolsettings->skgen_template);
04720 
04721             for(base= sce->base.first; base; base= next) {
04722                 next= base->next;
04723 
04724                 /* base->object= newlibadr_us(fd, sce->id.lib, base->object); */
04725                 base->object= newlibadr_us(fd, sce->id.lib, base->object);
04726                 
04727                 if(base->object==NULL) {
04728                     BKE_reportf_wrap(fd->reports, RPT_ERROR,
04729                                      "LIB ERROR: Object lost from scene:'%s\'\n",
04730                                      sce->id.name+2);
04731                     BLI_remlink(&sce->base, base);
04732                     if(base==sce->basact) sce->basact= NULL;
04733                     MEM_freeN(base);
04734                 }
04735             }
04736 
04737             SEQ_BEGIN(sce->ed, seq) {
04738                 if(seq->ipo) seq->ipo= newlibadr_us(fd, sce->id.lib, seq->ipo);
04739                 seq->scene_sound = NULL;
04740                 if(seq->scene) {
04741                     seq->scene= newlibadr(fd, sce->id.lib, seq->scene);
04742                     if(seq->scene) {
04743                         seq->scene_sound = sound_scene_add_scene_sound_defaults(sce, seq);
04744                     }
04745                 }
04746                 if(seq->scene_camera) seq->scene_camera= newlibadr(fd, sce->id.lib, seq->scene_camera);
04747                 if(seq->sound) {
04748                     seq->scene_sound = NULL;
04749                     if(seq->type == SEQ_HD_SOUND)
04750                         seq->type = SEQ_SOUND;
04751                     else
04752                         seq->sound= newlibadr(fd, sce->id.lib, seq->sound);
04753                     if (seq->sound) {
04754                         seq->sound->id.us++;
04755                         seq->scene_sound = sound_add_scene_sound_defaults(sce, seq);
04756                     }
04757                 }
04758                 seq->anim= NULL;
04759             }
04760             SEQ_END
04761 
04762 #ifdef DURIAN_CAMERA_SWITCH
04763             for(marker= sce->markers.first; marker; marker= marker->next) {
04764                 if(marker->camera) {
04765                     marker->camera= newlibadr(fd, sce->id.lib, marker->camera);
04766                 }
04767             }
04768 #else
04769             (void)marker;
04770 #endif
04771 
04772             if(sce->ed)
04773                 seq_update_muting(sce->ed);
04774             
04775             if(sce->nodetree) {
04776                 lib_link_ntree(fd, &sce->id, sce->nodetree);
04777                 composite_patch(sce->nodetree, sce);
04778             }
04779             
04780             for(srl= sce->r.layers.first; srl; srl= srl->next) {
04781                 srl->mat_override= newlibadr_us(fd, sce->id.lib, srl->mat_override);
04782                 srl->light_override= newlibadr_us(fd, sce->id.lib, srl->light_override);
04783             }
04784             /*Game Settings: Dome Warp Text*/
04785             sce->gm.dome.warptext= newlibadr(fd, sce->id.lib, sce->gm.dome.warptext);
04786 
04787             /* Motion Tracking */
04788             sce->clip= newlibadr_us(fd, sce->id.lib, sce->clip);
04789 
04790             sce->id.flag -= LIB_NEEDLINK;
04791         }
04792 
04793         sce= sce->id.next;
04794     }
04795 }
04796 
04797 static void link_recurs_seq(FileData *fd, ListBase *lb)
04798 {
04799     Sequence *seq;
04800 
04801     link_list(fd, lb);
04802 
04803     for(seq=lb->first; seq; seq=seq->next)
04804         if(seq->seqbase.first)
04805             link_recurs_seq(fd, &seq->seqbase);
04806 }
04807 
04808 static void direct_link_paint(FileData *fd, Paint **paint)
04809 {
04810 /* TODO. is this needed */
04811     (*paint)= newdataadr(fd, (*paint));
04812 }
04813 
04814 static void direct_link_scene(FileData *fd, Scene *sce)
04815 {
04816     Editing *ed;
04817     Sequence *seq;
04818     MetaStack *ms;
04819 
04820     sce->theDag = NULL;
04821     sce->dagisvalid = 0;
04822     sce->obedit= NULL;
04823     sce->stats= NULL;
04824     sce->fps_info= NULL;
04825     sce->customdata_mask_modal= 0;
04826     sce->lay_updated = 0;
04827 
04828     sound_create_scene(sce);
04829 
04830     /* set users to one by default, not in lib-link, this will increase it for compo nodes */
04831     sce->id.us= 1;
04832 
04833     link_list(fd, &(sce->base));
04834     
04835     sce->adt= newdataadr(fd, sce->adt);
04836     direct_link_animdata(fd, sce->adt);
04837     
04838     link_list(fd, &sce->keyingsets);
04839     direct_link_keyingsets(fd, &sce->keyingsets);
04840     
04841     sce->basact= newdataadr(fd, sce->basact);
04842     
04843     sce->toolsettings= newdataadr(fd, sce->toolsettings);
04844     if(sce->toolsettings) {
04845         direct_link_paint(fd, (Paint**)&sce->toolsettings->sculpt);
04846         direct_link_paint(fd, (Paint**)&sce->toolsettings->vpaint);
04847         direct_link_paint(fd, (Paint**)&sce->toolsettings->wpaint);
04848 
04849         sce->toolsettings->imapaint.paintcursor= NULL;
04850         sce->toolsettings->particle.paintcursor= NULL;
04851     }
04852 
04853     if(sce->ed) {
04854         ListBase *old_seqbasep= &((Editing *)sce->ed)->seqbase;
04855         
04856         ed= sce->ed= newdataadr(fd, sce->ed);
04857 
04858         ed->act_seq= newdataadr(fd, ed->act_seq);
04859 
04860         /* recursive link sequences, lb will be correctly initialized */
04861         link_recurs_seq(fd, &ed->seqbase);
04862 
04863         SEQ_BEGIN(ed, seq) {
04864             seq->seq1= newdataadr(fd, seq->seq1);
04865             seq->seq2= newdataadr(fd, seq->seq2);
04866             seq->seq3= newdataadr(fd, seq->seq3);
04867             /* a patch: after introduction of effects with 3 input strips */
04868             if(seq->seq3==NULL) seq->seq3= seq->seq2;
04869 
04870             seq->plugin= newdataadr(fd, seq->plugin);
04871             seq->effectdata= newdataadr(fd, seq->effectdata);
04872             
04873             if(seq->type & SEQ_EFFECT)
04874                 seq->flag |= SEQ_EFFECT_NOT_LOADED;
04875 
04876             if(seq->type == SEQ_SPEED) {
04877                 SpeedControlVars *s= seq->effectdata;
04878                 s->frameMap= NULL;
04879             }
04880 
04881             seq->strip= newdataadr(fd, seq->strip);
04882             if(seq->strip && seq->strip->done==0) {
04883                 seq->strip->done= 1;
04884 
04885                 if(seq->type == SEQ_IMAGE ||
04886                    seq->type == SEQ_MOVIE ||
04887                    seq->type == SEQ_RAM_SOUND ||
04888                    seq->type == SEQ_HD_SOUND) {
04889                     seq->strip->stripdata = newdataadr(
04890                         fd, seq->strip->stripdata);
04891                 } else {
04892                     seq->strip->stripdata = NULL;
04893                 }
04894                 if (seq->flag & SEQ_USE_CROP) {
04895                     seq->strip->crop = newdataadr(
04896                         fd, seq->strip->crop);
04897                 } else {
04898                     seq->strip->crop = NULL;
04899                 }
04900                 if (seq->flag & SEQ_USE_TRANSFORM) {
04901                     seq->strip->transform = newdataadr(
04902                         fd, seq->strip->transform);
04903                 } else {
04904                     seq->strip->transform = NULL;
04905                 }
04906                 if (seq->flag & SEQ_USE_PROXY) {
04907                     seq->strip->proxy = newdataadr(
04908                         fd, seq->strip->proxy);
04909                     seq->strip->proxy->anim = NULL;
04910                 } else {
04911                     seq->strip->proxy = NULL;
04912                 }
04913                 if (seq->flag & SEQ_USE_COLOR_BALANCE) {
04914                     seq->strip->color_balance = newdataadr(
04915                         fd, seq->strip->color_balance);
04916                 } else {
04917                     seq->strip->color_balance = NULL;
04918                 }
04919                 if (seq->strip->color_balance) {
04920                     // seq->strip->color_balance->gui = 0; // XXX - peter, is this relevant in 2.5?
04921                 }
04922             }
04923         }
04924         SEQ_END
04925         
04926         /* link metastack, slight abuse of structs here, have to restore pointer to internal part in struct */
04927         {
04928             Sequence temp;
04929             char *poin;
04930             intptr_t offset;
04931             
04932             offset= ((intptr_t)&(temp.seqbase)) - ((intptr_t)&temp);
04933             
04934             /* root pointer */
04935             if(ed->seqbasep == old_seqbasep) {
04936                 ed->seqbasep= &ed->seqbase;
04937             }
04938             else {
04939                 
04940                 poin= (char *)ed->seqbasep;
04941                 poin -= offset;
04942                 
04943                 poin= newdataadr(fd, poin);
04944                 if(poin) ed->seqbasep= (ListBase *)(poin+offset);
04945                 else ed->seqbasep= &ed->seqbase;
04946             }           
04947             /* stack */
04948             link_list(fd, &(ed->metastack));
04949             
04950             for(ms= ed->metastack.first; ms; ms= ms->next) {
04951                 ms->parseq= newdataadr(fd, ms->parseq);
04952                 
04953                 if(ms->oldbasep == old_seqbasep)
04954                     ms->oldbasep= &ed->seqbase;
04955                 else {
04956                     poin= (char *)ms->oldbasep;
04957                     poin -= offset;
04958                     poin= newdataadr(fd, poin);
04959                     if(poin) ms->oldbasep= (ListBase *)(poin+offset);
04960                     else ms->oldbasep= &ed->seqbase;
04961                 }
04962             }
04963         }
04964     }
04965     
04966     sce->r.avicodecdata = newdataadr(fd, sce->r.avicodecdata);
04967     if (sce->r.avicodecdata) {
04968         sce->r.avicodecdata->lpFormat = newdataadr(fd, sce->r.avicodecdata->lpFormat);
04969         sce->r.avicodecdata->lpParms = newdataadr(fd, sce->r.avicodecdata->lpParms);
04970     }
04971     
04972     sce->r.qtcodecdata = newdataadr(fd, sce->r.qtcodecdata);
04973     if (sce->r.qtcodecdata) {
04974         sce->r.qtcodecdata->cdParms = newdataadr(fd, sce->r.qtcodecdata->cdParms);
04975     }
04976     if (sce->r.ffcodecdata.properties) {
04977         sce->r.ffcodecdata.properties = newdataadr(
04978             fd, sce->r.ffcodecdata.properties);
04979         if (sce->r.ffcodecdata.properties) { 
04980             IDP_DirectLinkProperty(
04981                 sce->r.ffcodecdata.properties, 
04982                 (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
04983         }
04984     }
04985 
04986     link_list(fd, &(sce->markers));
04987     link_list(fd, &(sce->transform_spaces));
04988     link_list(fd, &(sce->r.layers));
04989 
04990     sce->nodetree= newdataadr(fd, sce->nodetree);
04991     if(sce->nodetree)
04992         direct_link_nodetree(fd, sce->nodetree);
04993 }
04994 
04995 /* ************ READ WM ***************** */
04996 
04997 static void direct_link_windowmanager(FileData *fd, wmWindowManager *wm)
04998 {
04999     wmWindow *win;
05000     
05001     wm->id.us= 1;
05002     link_list(fd, &(wm->windows));
05003     
05004     for(win= wm->windows.first; win; win= win->next) {
05005         win->ghostwin= NULL;
05006         win->eventstate= NULL;
05007         win->curswin= NULL;
05008         win->tweak= NULL;
05009 
05010         win->queue.first= win->queue.last= NULL;
05011         win->handlers.first= win->handlers.last= NULL;
05012         win->modalhandlers.first= win->modalhandlers.last= NULL;
05013         win->subwindows.first= win->subwindows.last= NULL;
05014         win->gesture.first= win->gesture.last= NULL;
05015 
05016         win->drawdata= NULL;
05017         win->drawmethod= -1;
05018         win->drawfail= 0;
05019     }
05020     
05021     wm->timers.first= wm->timers.last= NULL;
05022     wm->operators.first= wm->operators.last= NULL;
05023     wm->paintcursors.first= wm->paintcursors.last= NULL;
05024     wm->queue.first= wm->queue.last= NULL;
05025     BKE_reports_init(&wm->reports, RPT_STORE);
05026 
05027     wm->keyconfigs.first= wm->keyconfigs.last= NULL;
05028     wm->defaultconf= NULL;
05029     wm->addonconf= NULL;
05030     wm->userconf= NULL;
05031 
05032     wm->jobs.first= wm->jobs.last= NULL;
05033     wm->drags.first= wm->drags.last= NULL;
05034     
05035     wm->windrawable= NULL;
05036     wm->winactive= NULL;
05037     wm->initialized= 0;
05038     wm->op_undo_depth= 0;
05039 }
05040 
05041 static void lib_link_windowmanager(FileData *fd, Main *main)
05042 {
05043     wmWindowManager *wm;
05044     wmWindow *win;
05045     
05046     for(wm= main->wm.first; wm; wm= wm->id.next) {
05047         if(wm->id.flag & LIB_NEEDLINK) {
05048             for(win= wm->windows.first; win; win= win->next)
05049                 win->screen= newlibadr(fd, NULL, win->screen);
05050 
05051             wm->id.flag -= LIB_NEEDLINK;
05052         }
05053     }
05054 }
05055 
05056 /* ****************** READ GREASE PENCIL ***************** */
05057 
05058 /* relinks grease-pencil data - used for direct_link and old file linkage */
05059 static void direct_link_gpencil(FileData *fd, bGPdata *gpd)
05060 {
05061     bGPDlayer *gpl;
05062     bGPDframe *gpf;
05063     bGPDstroke *gps;
05064     
05065     /* we must firstly have some grease-pencil data to link! */
05066     if (gpd == NULL)
05067         return;
05068     
05069     /* relink layers */
05070     link_list(fd, &gpd->layers);
05071     
05072     for (gpl= gpd->layers.first; gpl; gpl= gpl->next) {
05073         /* relink frames */
05074         link_list(fd, &gpl->frames);
05075         gpl->actframe= newdataadr(fd, gpl->actframe);
05076         
05077         for (gpf= gpl->frames.first; gpf; gpf= gpf->next) {
05078             /* relink strokes (and their points) */
05079             link_list(fd, &gpf->strokes);
05080             
05081             for (gps= gpf->strokes.first; gps; gps= gps->next) {
05082                 gps->points= newdataadr(fd, gps->points);
05083             }
05084         }
05085     }
05086 }
05087 
05088 /* ****************** READ SCREEN ***************** */
05089 
05090 static void butspace_version_132(SpaceButs *buts)
05091 {
05092     buts->v2d.tot.xmin= 0.0f;
05093     buts->v2d.tot.ymin= 0.0f;
05094     buts->v2d.tot.xmax= 1279.0f;
05095     buts->v2d.tot.ymax= 228.0f;
05096 
05097     buts->v2d.min[0]= 256.0f;
05098     buts->v2d.min[1]= 42.0f;
05099 
05100     buts->v2d.max[0]= 2048.0f;
05101     buts->v2d.max[1]= 450.0f;
05102 
05103     buts->v2d.minzoom= 0.5f;
05104     buts->v2d.maxzoom= 1.21f;
05105 
05106     buts->v2d.scroll= 0;
05107     buts->v2d.keepzoom= 1;
05108     buts->v2d.keeptot= 1;
05109 }
05110 
05111 /* note: file read without screens option G_FILE_NO_UI; 
05112    check lib pointers in call below */
05113 static void lib_link_screen(FileData *fd, Main *main)
05114 {
05115     bScreen *sc;
05116     ScrArea *sa;
05117 
05118     for(sc= main->screen.first; sc; sc= sc->id.next) {
05119         if(sc->id.flag & LIB_NEEDLINK) {
05120             sc->id.us= 1;
05121             sc->scene= newlibadr(fd, sc->id.lib, sc->scene);
05122             sc->animtimer= NULL; /* saved in rare cases */
05123             
05124             sa= sc->areabase.first;
05125             while(sa) {
05126                 SpaceLink *sl;
05127                 
05128                 sa->full= newlibadr(fd, sc->id.lib, sa->full);
05129                 
05130                 for (sl= sa->spacedata.first; sl; sl= sl->next) {
05131                     if(sl->spacetype==SPACE_VIEW3D) {
05132                         View3D *v3d= (View3D*) sl;
05133                         BGpic *bgpic = NULL;
05134                         
05135                         v3d->camera= newlibadr(fd, sc->id.lib, v3d->camera);
05136                         v3d->ob_centre= newlibadr(fd, sc->id.lib, v3d->ob_centre);
05137                         
05138                         /* should be do_versions but not easy adding into the listbase */
05139                         if(v3d->bgpic) {
05140                             v3d->bgpic= newlibadr(fd, sc->id.lib, v3d->bgpic);
05141                             BLI_addtail(&v3d->bgpicbase, bgpic);
05142                             v3d->bgpic= NULL;
05143                         }
05144 
05145                         for(bgpic= v3d->bgpicbase.first; bgpic; bgpic= bgpic->next) {
05146                             bgpic->ima= newlibadr_us(fd, sc->id.lib, bgpic->ima);
05147                             bgpic->clip= newlibadr_us(fd, sc->id.lib, bgpic->clip);
05148                         }
05149                         if(v3d->localvd) {
05150                             v3d->localvd->camera= newlibadr(fd, sc->id.lib, v3d->localvd->camera);
05151                         }
05152                     }
05153                     else if(sl->spacetype==SPACE_IPO) {
05154                         SpaceIpo *sipo= (SpaceIpo *)sl;
05155                         bDopeSheet *ads= sipo->ads;
05156                         
05157                         if (ads) {
05158                             ads->source= newlibadr(fd, sc->id.lib, ads->source);
05159                             ads->filter_grp= newlibadr(fd, sc->id.lib, ads->filter_grp);
05160                         }
05161                     }
05162                     else if(sl->spacetype==SPACE_BUTS) {
05163                         SpaceButs *sbuts= (SpaceButs *)sl;
05164                         sbuts->pinid= newlibadr(fd, sc->id.lib, sbuts->pinid);
05165                         sbuts->mainbo= sbuts->mainb;
05166                         sbuts->mainbuser= sbuts->mainb;
05167                         if(main->versionfile<132)
05168                             butspace_version_132(sbuts);
05169                     }
05170                     else if(sl->spacetype==SPACE_FILE) {
05171                         SpaceFile *sfile= (SpaceFile *)sl;
05172                         sfile->files= NULL;
05173                         sfile->op= NULL;
05174                         sfile->layout= NULL;
05175                         sfile->folders_prev= NULL;
05176                         sfile->folders_next= NULL;
05177                     }
05178                     else if(sl->spacetype==SPACE_ACTION) {
05179                         SpaceAction *saction= (SpaceAction *)sl;
05180                         bDopeSheet *ads= &saction->ads;
05181                         
05182                         if (ads) {
05183                             ads->source= newlibadr(fd, sc->id.lib, ads->source);
05184                             ads->filter_grp= newlibadr(fd, sc->id.lib, ads->filter_grp);
05185                         }
05186                         
05187                         saction->action = newlibadr(fd, sc->id.lib, saction->action);
05188                     }
05189                     else if(sl->spacetype==SPACE_IMAGE) {
05190                         SpaceImage *sima= (SpaceImage *)sl;
05191 
05192                         sima->image= newlibadr_us(fd, sc->id.lib, sima->image);
05193                         
05194                         /* NOTE: pre-2.5, this was local data not lib data, but now we need this as lib data
05195                          * so fingers crossed this works fine!
05196                          */
05197                         sima->gpd= newlibadr_us(fd, sc->id.lib, sima->gpd);
05198                     }
05199                     else if(sl->spacetype==SPACE_NLA){
05200                         SpaceNla *snla= (SpaceNla *)sl;
05201                         bDopeSheet *ads= snla->ads;
05202                         
05203                         if (ads) {
05204                             ads->source= newlibadr(fd, sc->id.lib, ads->source);
05205                             ads->filter_grp= newlibadr(fd, sc->id.lib, ads->filter_grp);
05206                         }
05207                     }
05208                     else if(sl->spacetype==SPACE_TEXT) {
05209                         SpaceText *st= (SpaceText *)sl;
05210 
05211                         st->text= newlibadr(fd, sc->id.lib, st->text);
05212                         st->drawcache= NULL;
05213 
05214                     }
05215                     else if(sl->spacetype==SPACE_SCRIPT) {
05216 
05217                         SpaceScript *scpt= (SpaceScript *)sl;
05218                         /*scpt->script = NULL; - 2.45 set to null, better re-run the script */
05219                         if (scpt->script) {
05220                             scpt->script= newlibadr(fd, sc->id.lib, scpt->script);
05221                             if (scpt->script) {
05222                                 SCRIPT_SET_NULL(scpt->script)
05223                             }
05224                         }
05225                     }
05226                     else if(sl->spacetype==SPACE_OUTLINER) {
05227                         SpaceOops *so= (SpaceOops *)sl;
05228                         TreeStoreElem *tselem;
05229                         int a;
05230 
05231                         so->tree.first= so->tree.last= NULL;
05232                         so->search_tse.id= newlibadr(fd, NULL, so->search_tse.id);
05233                         
05234                         if(so->treestore) {
05235                             tselem= so->treestore->data;
05236                             for(a=0; a<so->treestore->usedelem; a++, tselem++) {
05237                                 tselem->id= newlibadr(fd, NULL, tselem->id);
05238                             }
05239                         }
05240                     }
05241                     else if(sl->spacetype==SPACE_NODE) {
05242                         SpaceNode *snode= (SpaceNode *)sl;
05243                         
05244                         snode->id= newlibadr(fd, sc->id.lib, snode->id);
05245                         snode->edittree= NULL;
05246                         
05247                         if (ELEM3(snode->treetype, NTREE_COMPOSIT, NTREE_SHADER, NTREE_TEXTURE)) {
05248                             /* internal data, a bit patchy */
05249                             snode->nodetree= NULL;
05250                             if(snode->id) {
05251                                 if(GS(snode->id->name)==ID_MA)
05252                                     snode->nodetree= ((Material *)snode->id)->nodetree;
05253                                 else if(GS(snode->id->name)==ID_WO)
05254                                     snode->nodetree= ((World *)snode->id)->nodetree;
05255                                 else if(GS(snode->id->name)==ID_LA)
05256                                     snode->nodetree= ((Lamp *)snode->id)->nodetree;
05257                                 else if(GS(snode->id->name)==ID_SCE)
05258                                     snode->nodetree= ((Scene *)snode->id)->nodetree;
05259                                 else if(GS(snode->id->name)==ID_TE)
05260                                     snode->nodetree= ((Tex *)snode->id)->nodetree;
05261                             }
05262                         }
05263                         else {
05264                             snode->nodetree= newlibadr_us(fd, sc->id.lib, snode->nodetree);
05265                         }
05266                         
05267                         snode->linkdrag.first = snode->linkdrag.last = NULL;
05268                     }
05269                     else if(sl->spacetype==SPACE_CLIP) {
05270                         SpaceClip *sclip= (SpaceClip *)sl;
05271 
05272                         sclip->clip= newlibadr_us(fd, sc->id.lib, sclip->clip);
05273 
05274                         sclip->scopes.track_preview = NULL;
05275                         sclip->scopes.ok = 0;
05276                     }
05277                 }
05278                 sa= sa->next;
05279             }
05280             sc->id.flag -= LIB_NEEDLINK;
05281         }
05282     }
05283 }
05284 
05285 /* Only for undo files, or to restore a screen after reading without UI... */
05286 static void *restore_pointer_by_name(Main *mainp, ID *id, int user)
05287 {
05288         
05289     if(id) {
05290         ListBase *lb= which_libbase(mainp, GS(id->name));
05291         
05292         if(lb) {    // there's still risk of checking corrupt mem (freed Ids in oops)
05293             ID *idn= lb->first;
05294             char *name= id->name+2;
05295             
05296             while(idn) {
05297                 if(idn->name[2]==name[0] && strcmp(idn->name+2, name)==0) {
05298                     if(idn->lib==id->lib) {
05299                         if(user && idn->us==0) idn->us++;
05300                         break;
05301                     }
05302                 }
05303                 idn= idn->next;
05304             }
05305             return idn;
05306         }
05307     }
05308     return NULL;
05309 }
05310 
05311 /* called from kernel/blender.c */
05312 /* used to link a file (without UI) to the current UI */
05313 /* note that it assumes the old pointers in UI are still valid, so old Main is not freed */
05314 void lib_link_screen_restore(Main *newmain, bScreen *curscreen, Scene *curscene)
05315 {
05316     wmWindow *win;
05317     wmWindowManager *wm;
05318     bScreen *sc;
05319     ScrArea *sa;
05320 
05321     /* first windowmanager */
05322     for(wm= newmain->wm.first; wm; wm= wm->id.next) {
05323         for(win= wm->windows.first; win; win= win->next) {
05324             win->screen= restore_pointer_by_name(newmain, (ID *)win->screen, 1);
05325             
05326             if(win->screen==NULL)
05327                 win->screen= curscreen;
05328 
05329             win->screen->winid= win->winid;
05330         }
05331     }
05332     
05333     
05334     for(sc= newmain->screen.first; sc; sc= sc->id.next) {
05335         Scene *oldscene= sc->scene;
05336 
05337         sc->scene= restore_pointer_by_name(newmain, (ID *)sc->scene, 1);
05338         if(sc->scene==NULL)
05339             sc->scene= curscene;
05340 
05341         /* keep cursor location through undo */
05342         copy_v3_v3(sc->scene->cursor, oldscene->cursor);
05343 
05344         sa= sc->areabase.first;
05345         while(sa) {
05346             SpaceLink *sl;
05347 
05348             for (sl= sa->spacedata.first; sl; sl= sl->next) {
05349                 if(sl->spacetype==SPACE_VIEW3D) {
05350                     View3D *v3d= (View3D*) sl;
05351                     BGpic *bgpic;
05352                     ARegion *ar;
05353                     
05354                     if(v3d->scenelock)
05355                         v3d->camera= NULL; /* always get from scene */
05356                     else
05357                         v3d->camera= restore_pointer_by_name(newmain, (ID *)v3d->camera, 1);
05358                     if(v3d->camera==NULL)
05359                         v3d->camera= sc->scene->camera;
05360                     v3d->ob_centre= restore_pointer_by_name(newmain, (ID *)v3d->ob_centre, 1);
05361                     
05362                     for(bgpic= v3d->bgpicbase.first; bgpic; bgpic= bgpic->next) {
05363                         bgpic->ima= restore_pointer_by_name(newmain, (ID *)bgpic->ima, 1);
05364                         bgpic->clip= restore_pointer_by_name(newmain, (ID *)bgpic->clip, 1);
05365                     }
05366                     if(v3d->localvd) {
05367                         /*Base *base;*/
05368 
05369                         v3d->localvd->camera= sc->scene->camera;
05370                         
05371                         /* localview can become invalid during undo/redo steps, so we exit it when no could be found */
05372                         /* XXX  regionlocalview ?
05373                         for(base= sc->scene->base.first; base; base= base->next) {
05374                             if(base->lay & v3d->lay) break;
05375                         }
05376                         if(base==NULL) {
05377                             v3d->lay= v3d->localvd->lay;
05378                             v3d->layact= v3d->localvd->layact;
05379                             MEM_freeN(v3d->localvd); 
05380                             v3d->localvd= NULL;
05381                         }
05382                         */
05383                     }
05384                     else if(v3d->scenelock) v3d->lay= sc->scene->lay;
05385 
05386                     /* not very nice, but could help */
05387                     if((v3d->layact & v3d->lay)==0) v3d->layact= v3d->lay;
05388                     
05389                     /* free render engines for now */
05390                     for(ar= sa->regionbase.first; ar; ar= ar->next) {
05391                         RegionView3D *rv3d= ar->regiondata;
05392 
05393                         if(rv3d && rv3d->render_engine) {
05394                             RE_engine_free(rv3d->render_engine);
05395                             rv3d->render_engine= NULL;
05396                         }
05397                     }
05398                 }
05399                 else if(sl->spacetype==SPACE_IPO) {
05400                     SpaceIpo *sipo= (SpaceIpo *)sl;
05401                     bDopeSheet *ads= sipo->ads;
05402                     
05403                     if (ads) {
05404                         ads->source= restore_pointer_by_name(newmain, (ID *)ads->source, 1);
05405                         
05406                         if (ads->filter_grp)
05407                             ads->filter_grp= restore_pointer_by_name(newmain, (ID *)ads->filter_grp, 0);
05408                     }
05409                 }
05410                 else if(sl->spacetype==SPACE_BUTS) {
05411                     SpaceButs *sbuts= (SpaceButs *)sl;
05412                     sbuts->pinid = restore_pointer_by_name(newmain, sbuts->pinid, 0);
05413                     //XXX if (sbuts->ri) sbuts->ri->curtile = 0;
05414                 }
05415                 else if(sl->spacetype==SPACE_FILE) {
05416                     
05417                     SpaceFile *sfile= (SpaceFile *)sl;
05418                     sfile->op= NULL;
05419                 }
05420                 else if(sl->spacetype==SPACE_ACTION) {
05421                     SpaceAction *saction= (SpaceAction *)sl;
05422                     
05423                     saction->action = restore_pointer_by_name(newmain, (ID *)saction->action, 1);
05424                     saction->ads.source= restore_pointer_by_name(newmain, (ID *)saction->ads.source, 1);
05425 
05426                     if (saction->ads.filter_grp)
05427                         saction->ads.filter_grp= restore_pointer_by_name(newmain, (ID *)saction->ads.filter_grp, 0);
05428                 }
05429                 else if(sl->spacetype==SPACE_IMAGE) {
05430                     SpaceImage *sima= (SpaceImage *)sl;
05431 
05432                     sima->image= restore_pointer_by_name(newmain, (ID *)sima->image, 1);
05433 
05434                     sima->scopes.waveform_1 = NULL;
05435                     sima->scopes.waveform_2 = NULL;
05436                     sima->scopes.waveform_3 = NULL;
05437                     sima->scopes.vecscope = NULL;
05438                     sima->scopes.ok = 0;
05439                     
05440                     /* NOTE: pre-2.5, this was local data not lib data, but now we need this as lib data
05441                      * so assume that here we're doing for undo only...
05442                      */
05443                     sima->gpd= restore_pointer_by_name(newmain, (ID *)sima->gpd, 1);
05444                 }
05445                 else if(sl->spacetype==SPACE_NLA){
05446                     SpaceNla *snla= (SpaceNla *)sl;
05447                     bDopeSheet *ads= snla->ads;
05448                     
05449                     if (ads) {
05450                         ads->source= restore_pointer_by_name(newmain, (ID *)ads->source, 1);
05451                         
05452                         if (ads->filter_grp)
05453                             ads->filter_grp= restore_pointer_by_name(newmain, (ID *)ads->filter_grp, 0);
05454                     }
05455                 }
05456                 else if(sl->spacetype==SPACE_TEXT) {
05457                     SpaceText *st= (SpaceText *)sl;
05458 
05459                     st->text= restore_pointer_by_name(newmain, (ID *)st->text, 1);
05460                     if(st->text==NULL) st->text= newmain->text.first;
05461                 }
05462                 else if(sl->spacetype==SPACE_SCRIPT) {
05463                     SpaceScript *scpt= (SpaceScript *)sl;
05464                     
05465                     scpt->script= restore_pointer_by_name(newmain, (ID *)scpt->script, 1);
05466                     
05467                     /*sc->script = NULL; - 2.45 set to null, better re-run the script */
05468                     if (scpt->script) {
05469                         SCRIPT_SET_NULL(scpt->script)
05470                     }
05471                 }
05472                 else if(sl->spacetype==SPACE_OUTLINER) {
05473                     SpaceOops *so= (SpaceOops *)sl;
05474                     int a;
05475                     
05476                     so->search_tse.id= restore_pointer_by_name(newmain, so->search_tse.id, 0);
05477                     
05478                     if(so->treestore) {
05479                         TreeStore *ts= so->treestore;
05480                         TreeStoreElem *tselem=ts->data;
05481                         for(a=0; a<ts->usedelem; a++, tselem++) {
05482                             tselem->id= restore_pointer_by_name(newmain, tselem->id, 0);
05483                         }
05484                     }
05485                 }
05486                 else if(sl->spacetype==SPACE_NODE) {
05487                     SpaceNode *snode= (SpaceNode *)sl;
05488                     
05489                     snode->id= restore_pointer_by_name(newmain, snode->id, 1);
05490                     snode->edittree= NULL;
05491                     
05492                     if (ELEM3(snode->treetype, NTREE_COMPOSIT, NTREE_SHADER, NTREE_TEXTURE)) {
05493                         snode->nodetree= NULL;
05494                         if(snode->id) {
05495                             if(GS(snode->id->name)==ID_MA)
05496                                 snode->nodetree= ((Material *)snode->id)->nodetree;
05497                             else if(GS(snode->id->name)==ID_SCE)
05498                                 snode->nodetree= ((Scene *)snode->id)->nodetree;
05499                             else if(GS(snode->id->name)==ID_TE)
05500                                 snode->nodetree= ((Tex *)snode->id)->nodetree;
05501                         }
05502                     }
05503                     else {
05504                         snode->nodetree= restore_pointer_by_name(newmain, &snode->nodetree->id, 1);
05505                     }
05506                 }
05507                 else if(sl->spacetype==SPACE_CLIP) {
05508                     SpaceClip *sclip= (SpaceClip *)sl;
05509 
05510                     sclip->clip= restore_pointer_by_name(newmain, (ID *)sclip->clip, 1);
05511 
05512                     sclip->scopes.ok = 0;
05513                 }
05514             }
05515             sa= sa->next;
05516         }
05517     }
05518 }
05519 
05520 static void direct_link_region(FileData *fd, ARegion *ar, int spacetype)
05521 {
05522     Panel *pa;
05523 
05524     link_list(fd, &(ar->panels));
05525 
05526     for(pa= ar->panels.first; pa; pa=pa->next) {
05527         pa->paneltab= newdataadr(fd, pa->paneltab);
05528         pa->runtime_flag= 0;
05529         pa->activedata= NULL;
05530         pa->type= NULL;
05531     }
05532     
05533     ar->regiondata= newdataadr(fd, ar->regiondata);
05534     if(ar->regiondata) {
05535         if(spacetype==SPACE_VIEW3D) {
05536             RegionView3D *rv3d= ar->regiondata;
05537             
05538             rv3d->localvd= newdataadr(fd, rv3d->localvd);
05539             rv3d->clipbb= newdataadr(fd, rv3d->clipbb);
05540             
05541             rv3d->depths= NULL;
05542             rv3d->ri= NULL;
05543             rv3d->render_engine= NULL;
05544             rv3d->sms= NULL;
05545             rv3d->smooth_timer= NULL;
05546         }
05547     }
05548     
05549     ar->v2d.tab_offset= NULL;
05550     ar->v2d.tab_num= 0;
05551     ar->v2d.tab_cur= 0;
05552     ar->handlers.first= ar->handlers.last= NULL;
05553     ar->uiblocks.first= ar->uiblocks.last= NULL;
05554     ar->headerstr= NULL;
05555     ar->swinid= 0;
05556     ar->type= NULL;
05557     ar->swap= 0;
05558     ar->do_draw= 0;
05559     memset(&ar->drawrct, 0, sizeof(ar->drawrct));
05560 }
05561 
05562 /* for the saved 2.50 files without regiondata */
05563 /* and as patch for 2.48 and older */
05564 static void view3d_split_250(View3D *v3d, ListBase *regions)
05565 {
05566     ARegion *ar;
05567     
05568     for(ar= regions->first; ar; ar= ar->next) {
05569         if(ar->regiontype==RGN_TYPE_WINDOW && ar->regiondata==NULL) {
05570             RegionView3D *rv3d;
05571             
05572             rv3d= ar->regiondata= MEM_callocN(sizeof(RegionView3D), "region v3d patch");
05573             rv3d->persp= v3d->persp;
05574             rv3d->view= v3d->view;
05575             rv3d->dist= v3d->dist;
05576             copy_v3_v3(rv3d->ofs, v3d->ofs);
05577             copy_qt_qt(rv3d->viewquat, v3d->viewquat);
05578         }
05579     }
05580 
05581     /* this was not initialized correct always */
05582     if(v3d->twtype == 0)
05583         v3d->twtype= V3D_MANIP_TRANSLATE;
05584 }
05585 
05586 static void direct_link_screen(FileData *fd, bScreen *sc)
05587 {
05588     ScrArea *sa;
05589     ScrVert *sv;
05590     ScrEdge *se;
05591     int a;
05592     
05593     link_list(fd, &(sc->vertbase));
05594     link_list(fd, &(sc->edgebase));
05595     link_list(fd, &(sc->areabase));
05596     sc->regionbase.first= sc->regionbase.last= NULL;
05597     sc->context= NULL;
05598 
05599     sc->mainwin= sc->subwinactive= 0;   /* indices */
05600     sc->swap= 0;
05601     
05602     /* hacky patch... but people have been saving files with the verse-blender,
05603        causing the handler to keep running for ever, with no means to disable it */
05604     for(a=0; a<SCREEN_MAXHANDLER; a+=2) {
05605         if( sc->handler[a]==SCREEN_HANDLER_VERSE) {
05606             sc->handler[a]= 0;
05607             break;
05608         }
05609     }
05610     
05611     /* edges */
05612     for(se= sc->edgebase.first; se; se= se->next) {
05613         se->v1= newdataadr(fd, se->v1);
05614         se->v2= newdataadr(fd, se->v2);
05615         if( (intptr_t)se->v1 > (intptr_t)se->v2) {
05616             sv= se->v1;
05617             se->v1= se->v2;
05618             se->v2= sv;
05619         }
05620 
05621         if(se->v1==NULL) {
05622             printf("error reading screen... file corrupt\n");
05623             se->v1= se->v2;
05624         }
05625     }
05626 
05627     /* areas */
05628     for(sa= sc->areabase.first; sa; sa= sa->next) {
05629         SpaceLink *sl;
05630         ARegion *ar;
05631 
05632         link_list(fd, &(sa->spacedata));
05633         link_list(fd, &(sa->regionbase));
05634 
05635         sa->handlers.first= sa->handlers.last= NULL;
05636         sa->type= NULL; /* spacetype callbacks */
05637         
05638         for(ar= sa->regionbase.first; ar; ar= ar->next)
05639             direct_link_region(fd, ar, sa->spacetype);
05640         
05641         /* accident can happen when read/save new file with older version */
05642         /* 2.50: we now always add spacedata for info */
05643         if(sa->spacedata.first==NULL) {
05644             SpaceInfo *sinfo= MEM_callocN(sizeof(SpaceInfo), "spaceinfo");
05645             sa->spacetype= sinfo->spacetype= SPACE_INFO;
05646             BLI_addtail(&sa->spacedata, sinfo);
05647         }
05648         /* add local view3d too */
05649         else if(sa->spacetype==SPACE_VIEW3D)
05650             view3d_split_250(sa->spacedata.first, &sa->regionbase);
05651         
05652         for (sl= sa->spacedata.first; sl; sl= sl->next) {
05653             link_list(fd, &(sl->regionbase));
05654 
05655             for(ar= sl->regionbase.first; ar; ar= ar->next)
05656                 direct_link_region(fd, ar, sl->spacetype);
05657 
05658             if (sl->spacetype==SPACE_VIEW3D) {
05659                 View3D *v3d= (View3D*) sl;
05660                 BGpic *bgpic;
05661 
05662                 v3d->flag |= V3D_INVALID_BACKBUF;
05663 
05664                 link_list(fd, &(v3d->bgpicbase));
05665 
05666                 /* should be do_versions except this doesnt fit well there */
05667                 if(v3d->bgpic) {
05668                     bgpic= newdataadr(fd, v3d->bgpic);
05669                     BLI_addtail(&v3d->bgpicbase, bgpic);
05670                     v3d->bgpic= NULL;
05671                 }
05672 
05673                 for(bgpic= v3d->bgpicbase.first; bgpic; bgpic= bgpic->next)
05674                     bgpic->iuser.ok= 1;
05675 
05676                 if(v3d->gpd) {
05677                     v3d->gpd= newdataadr(fd, v3d->gpd);
05678                     direct_link_gpencil(fd, v3d->gpd);
05679                 }
05680                 v3d->localvd= newdataadr(fd, v3d->localvd);
05681                 v3d->afterdraw_transp.first= v3d->afterdraw_transp.last= NULL;
05682                 v3d->afterdraw_xray.first= v3d->afterdraw_xray.last= NULL;
05683                 v3d->afterdraw_xraytransp.first= v3d->afterdraw_xraytransp.last= NULL;
05684                 v3d->properties_storage= NULL;
05685 
05686                 /* render can be quite heavy, set to wire on load */
05687                 if(v3d->drawtype == OB_RENDER)
05688                     v3d->drawtype = OB_WIRE;
05689                 
05690                 view3d_split_250(v3d, &sl->regionbase);
05691             }
05692             else if (sl->spacetype==SPACE_IPO) {
05693                 SpaceIpo *sipo= (SpaceIpo*)sl;
05694                 
05695                 sipo->ads= newdataadr(fd, sipo->ads);
05696                 sipo->ghostCurves.first= sipo->ghostCurves.last= NULL;
05697             }
05698             else if (sl->spacetype==SPACE_NLA) {
05699                 SpaceNla *snla= (SpaceNla*)sl;
05700                 
05701                 snla->ads= newdataadr(fd, snla->ads);
05702             }
05703             else if (sl->spacetype==SPACE_OUTLINER) {
05704                 SpaceOops *soops= (SpaceOops*) sl;
05705                 
05706                 soops->treestore= newdataadr(fd, soops->treestore);
05707                 if(soops->treestore) {
05708                     soops->treestore->data= newdataadr(fd, soops->treestore->data);
05709                     /* we only saved what was used */
05710                     soops->treestore->totelem= soops->treestore->usedelem;
05711                     soops->storeflag |= SO_TREESTORE_CLEANUP;   // at first draw
05712                 }
05713             }
05714             else if(sl->spacetype==SPACE_IMAGE) {
05715                 SpaceImage *sima= (SpaceImage *)sl;
05716                 
05717                 sima->cumap= newdataadr(fd, sima->cumap);
05718                 if(sima->cumap)
05719                     direct_link_curvemapping(fd, sima->cumap);
05720                 
05721                 sima->iuser.scene= NULL;
05722                 sima->iuser.ok= 1;
05723                 sima->scopes.waveform_1 = NULL;
05724                 sima->scopes.waveform_2 = NULL;
05725                 sima->scopes.waveform_3 = NULL;
05726                 sima->scopes.vecscope = NULL;
05727                 sima->scopes.ok = 0;
05728                 
05729                 /* WARNING: gpencil data is no longer stored directly in sima after 2.5 
05730                  * so sacrifice a few old files for now to avoid crashes with new files!
05731                  * committed: r28002 */
05732 #if 0
05733                 sima->gpd= newdataadr(fd, sima->gpd);
05734                 if (sima->gpd)
05735                     direct_link_gpencil(fd, sima->gpd);
05736 #endif
05737             }
05738             else if(sl->spacetype==SPACE_NODE) {
05739                 SpaceNode *snode= (SpaceNode *)sl;
05740                 
05741                 if(snode->gpd) {
05742                     snode->gpd= newdataadr(fd, snode->gpd);
05743                     direct_link_gpencil(fd, snode->gpd);
05744                 }
05745             }
05746             else if(sl->spacetype==SPACE_TIME) {
05747                 SpaceTime *stime= (SpaceTime *)sl;
05748                 stime->caches.first= stime->caches.last= NULL;
05749             }
05750             else if(sl->spacetype==SPACE_LOGIC) {
05751                 SpaceLogic *slogic= (SpaceLogic *)sl;
05752                     
05753                 if(slogic->gpd) {
05754                     slogic->gpd= newdataadr(fd, slogic->gpd);
05755                     direct_link_gpencil(fd, slogic->gpd);
05756                 }
05757             }
05758             else if(sl->spacetype==SPACE_SEQ) {
05759                 SpaceSeq *sseq= (SpaceSeq *)sl;
05760                 if(sseq->gpd) {
05761                     sseq->gpd= newdataadr(fd, sseq->gpd);
05762                     direct_link_gpencil(fd, sseq->gpd);
05763                 }
05764             }
05765             else if(sl->spacetype==SPACE_BUTS) {
05766                 SpaceButs *sbuts= (SpaceButs *)sl;
05767                 sbuts->path= NULL;
05768                 sbuts->texuser= NULL;
05769             }
05770             else if(sl->spacetype==SPACE_CONSOLE) {
05771                 SpaceConsole *sconsole= (SpaceConsole *)sl;
05772                 ConsoleLine *cl, *cl_next;
05773                 
05774                 link_list(fd, &sconsole->scrollback);
05775                 link_list(fd, &sconsole->history);
05776                 
05777                 //for(cl= sconsole->scrollback.first; cl; cl= cl->next)
05778                 //  cl->line= newdataadr(fd, cl->line);
05779                 
05780                 /*comma expressions, (e.g. expr1, expr2, expr3) evalutate each expression,
05781                   from left to right.  the right-most expression sets the result of the comma
05782                   expression as a whole*/
05783                 for(cl= sconsole->history.first; cl; cl= cl_next) {
05784                     cl_next= cl->next;
05785                     cl->line= newdataadr(fd, cl->line);
05786                     if (cl->line) {
05787                         /* the allocted length is not written, so reset here */
05788                         cl->len_alloc= cl->len + 1;
05789                     }
05790                     else {
05791                         BLI_remlink(&sconsole->history, cl);
05792                         MEM_freeN(cl);
05793                     }
05794                 }
05795             }
05796             else if(sl->spacetype==SPACE_FILE) {
05797                 SpaceFile *sfile= (SpaceFile *)sl;
05798                 
05799                 /* this sort of info is probably irrelevant for reloading...
05800                  * plus, it isn't saved to files yet!
05801                  */
05802                 sfile->folders_prev= sfile->folders_next= NULL;
05803                 sfile->files= NULL;
05804                 sfile->layout= NULL;
05805                 sfile->op= NULL;
05806                 sfile->params= newdataadr(fd, sfile->params);
05807             }
05808         }
05809         
05810         sa->actionzones.first= sa->actionzones.last= NULL;
05811 
05812         sa->v1= newdataadr(fd, sa->v1);
05813         sa->v2= newdataadr(fd, sa->v2);
05814         sa->v3= newdataadr(fd, sa->v3);
05815         sa->v4= newdataadr(fd, sa->v4);
05816     }
05817 }
05818 
05819 /* ********** READ LIBRARY *************** */
05820 
05821 
05822 static void direct_link_library(FileData *fd, Library *lib, Main *main)
05823 {
05824     Main *newmain;
05825     
05826     for(newmain= fd->mainlist.first; newmain; newmain= newmain->next) {
05827         if(newmain->curlib) {
05828             if(BLI_path_cmp(newmain->curlib->filepath, lib->filepath) == 0) {
05829                 BKE_reportf_wrap(fd->reports, RPT_WARNING,
05830                                  "Library '%s', '%s' had multiple instances, save and reload!",
05831                                  lib->name, lib->filepath);
05832 
05833                 change_idid_adr(&fd->mainlist, fd, lib, newmain->curlib);
05834 //              change_idid_adr_fd(fd, lib, newmain->curlib);
05835                 
05836                 BLI_remlink(&main->library, lib);
05837                 MEM_freeN(lib);
05838 
05839 
05840                 return;
05841             }
05842         }
05843     }
05844     /* make sure we have full path in lib->filename */
05845     BLI_strncpy(lib->filepath, lib->name, sizeof(lib->name));
05846     cleanup_path(fd->relabase, lib->filepath);
05847     
05848 //  printf("direct_link_library: name %s\n", lib->name);
05849 //  printf("direct_link_library: filename %s\n", lib->filename);
05850     
05851     /* new main */
05852     newmain= MEM_callocN(sizeof(Main), "directlink");
05853     BLI_addtail(&fd->mainlist, newmain);
05854     newmain->curlib= lib;
05855 
05856     lib->parent= NULL;
05857 }
05858 
05859 static void lib_link_library(FileData *UNUSED(fd), Main *main)
05860 {
05861     Library *lib;
05862     for(lib= main->library.first; lib; lib= lib->id.next) {
05863         lib->id.us= 1;
05864     }
05865 }
05866 
05867 /* Always call this once you have loaded new library data to set the relative paths correctly in relation to the blend file */
05868 static void fix_relpaths_library(const char *basepath, Main *main)
05869 {
05870     Library *lib;
05871     /* BLO_read_from_memory uses a blank filename */
05872     if (basepath==NULL || basepath[0] == '\0') {
05873         for(lib= main->library.first; lib; lib= lib->id.next) {
05874             /* when loading a linked lib into a file which has not been saved,
05875              * there is nothing we can be relative to, so instead we need to make
05876              * it absolute. This can happen when appending an object with a relative
05877              * link into an unsaved blend file. See [#27405].
05878              * The remap relative option will make it relative again on save - campbell */
05879             if (strncmp(lib->name, "//", 2)==0) {
05880                 BLI_strncpy(lib->name, lib->filepath, sizeof(lib->name));
05881             }
05882         }
05883     }
05884     else {
05885         for(lib= main->library.first; lib; lib= lib->id.next) {
05886             /* Libraries store both relative and abs paths, recreate relative paths,
05887              * relative to the blend file since indirectly linked libs will be relative to their direct linked library */
05888             if (strncmp(lib->name, "//", 2)==0) { /* if this is relative to begin with? */
05889                 BLI_strncpy(lib->name, lib->filepath, sizeof(lib->name));
05890                 BLI_path_rel(lib->name, basepath);
05891             }
05892         }
05893     }
05894 }
05895 
05896 /* ************ READ SPEAKER ***************** */
05897 
05898 static void lib_link_speaker(FileData *fd, Main *main)
05899 {
05900     Speaker *spk;
05901 
05902     spk= main->speaker.first;
05903     while(spk) {
05904         if(spk->id.flag & LIB_NEEDLINK) {
05905             if (spk->adt) lib_link_animdata(fd, &spk->id, spk->adt);
05906 
05907             spk->sound= newlibadr(fd, spk->id.lib, spk->sound);
05908             if (spk->sound) {
05909                 spk->sound->id.us++;
05910             }
05911 
05912             spk->id.flag -= LIB_NEEDLINK;
05913         }
05914         spk= spk->id.next;
05915     }
05916 }
05917 
05918 static void direct_link_speaker(FileData *fd, Speaker *spk)
05919 {
05920     spk->adt= newdataadr(fd, spk->adt);
05921     direct_link_animdata(fd, spk->adt);
05922 
05923     /*spk->sound= newdataadr(fd, spk->sound);
05924     direct_link_sound(fd, spk->sound);*/
05925 }
05926 
05927 /* ************** READ SOUND ******************* */
05928 
05929 static void direct_link_sound(FileData *fd, bSound *sound)
05930 {
05931     sound->handle = NULL;
05932     sound->playback_handle = NULL;
05933     sound->waveform = NULL;
05934 
05935     // versioning stuff, if there was a cache, then we enable caching:
05936     if(sound->cache)
05937     {
05938         sound->flags |= SOUND_FLAGS_CACHING;
05939         sound->cache = NULL;
05940     }
05941 
05942     sound->packedfile = direct_link_packedfile(fd, sound->packedfile);
05943     sound->newpackedfile = direct_link_packedfile(fd, sound->newpackedfile);
05944 }
05945 
05946 static void lib_link_sound(FileData *fd, Main *main)
05947 {
05948     bSound *sound;
05949 
05950     sound= main->sound.first;
05951     while(sound) {
05952         if(sound->id.flag & LIB_NEEDLINK) {
05953             sound->id.flag -= LIB_NEEDLINK;
05954             sound->ipo= newlibadr_us(fd, sound->id.lib, sound->ipo); // XXX depreceated - old animation system
05955             
05956             sound_load(main, sound);
05957         }
05958         sound= sound->id.next;
05959     }
05960 }
05961 /* ***************** READ GROUP *************** */
05962 
05963 static void direct_link_group(FileData *fd, Group *group)
05964 {
05965     link_list(fd, &group->gobject);
05966 }
05967 
05968 static void lib_link_group(FileData *fd, Main *main)
05969 {
05970     Group *group= main->group.first;
05971     GroupObject *go;
05972     int add_us;
05973     
05974     while(group) {
05975         if(group->id.flag & LIB_NEEDLINK) {
05976             group->id.flag -= LIB_NEEDLINK;
05977             
05978             add_us= 0;
05979             
05980             go= group->gobject.first;
05981             while(go) {
05982                 go->ob= newlibadr(fd, group->id.lib, go->ob);
05983                 if(go->ob) {
05984                     go->ob->flag |= OB_FROMGROUP;
05985                     /* if group has an object, it increments user... */
05986                     add_us= 1;
05987                     if(go->ob->id.us==0) 
05988                         go->ob->id.us= 1;
05989                 }
05990                 go= go->next;
05991             }
05992             if(add_us) group->id.us++;
05993             rem_from_group(group, NULL, NULL, NULL);    /* removes NULL entries */
05994         }
05995         group= group->id.next;
05996     }
05997 }
05998 
05999 /* ***************** READ MOVIECLIP *************** */
06000 
06001 static void direct_link_movieReconstruction(FileData *fd, MovieTrackingReconstruction *reconstruction)
06002 {
06003     reconstruction->cameras= newdataadr(fd, reconstruction->cameras);
06004 }
06005 
06006 static void direct_link_movieTracks(FileData *fd, ListBase *tracksbase)
06007 {
06008     MovieTrackingTrack *track;
06009 
06010     link_list(fd, tracksbase);
06011 
06012     track= tracksbase->first;
06013     while(track) {
06014         track->markers= newdataadr(fd, track->markers);
06015 
06016         track= track->next;
06017     }
06018 }
06019 
06020 static void direct_link_movieclip(FileData *fd, MovieClip *clip)
06021 {
06022     MovieTracking *tracking= &clip->tracking;
06023     MovieTrackingObject *object;
06024 
06025     if(fd->movieclipmap) clip->cache= newmclipadr(fd, clip->cache);
06026     else clip->cache= NULL;
06027 
06028     if(fd->movieclipmap) clip->tracking.camera.intrinsics= newmclipadr(fd, clip->tracking.camera.intrinsics);
06029     else clip->tracking.camera.intrinsics= NULL;
06030 
06031     direct_link_movieTracks(fd, &tracking->tracks);
06032     direct_link_movieReconstruction(fd, &tracking->reconstruction);
06033 
06034     clip->tracking.act_track= newdataadr(fd, clip->tracking.act_track);
06035 
06036     clip->anim= NULL;
06037     clip->tracking_context= NULL;
06038     clip->tracking.stats= NULL;
06039 
06040     clip->tracking.stabilization.ok= 0;
06041     clip->tracking.stabilization.scaleibuf= NULL;
06042     clip->tracking.stabilization.rot_track= newdataadr(fd, clip->tracking.stabilization.rot_track);
06043 
06044     link_list(fd, &tracking->objects);
06045 
06046     object= tracking->objects.first;
06047     while(object) {
06048         direct_link_movieTracks(fd, &object->tracks);
06049         direct_link_movieReconstruction(fd, &object->reconstruction);
06050 
06051         object= object->next;
06052     }
06053 }
06054 
06055 static void lib_link_movieclip(FileData *fd, Main *main)
06056 {
06057     MovieClip *clip;
06058 
06059     clip= main->movieclip.first;
06060     while(clip) {
06061         if(clip->id.flag & LIB_NEEDLINK) {
06062             clip->gpd= newlibadr_us(fd, clip->id.lib, clip->gpd);
06063 
06064             clip->id.flag -= LIB_NEEDLINK;
06065         }
06066         clip= clip->id.next;
06067     }
06068 }
06069 
06070 /* ************** GENERAL & MAIN ******************** */
06071 
06072 
06073 static const char *dataname(short id_code)
06074 {
06075     
06076     switch( id_code ) {
06077         case ID_OB: return "Data from OB";
06078         case ID_ME: return "Data from ME";
06079         case ID_IP: return "Data from IP";
06080         case ID_SCE: return "Data from SCE";
06081         case ID_MA: return "Data from MA";
06082         case ID_TE: return "Data from TE";
06083         case ID_CU: return "Data from CU";
06084         case ID_GR: return "Data from GR";
06085         case ID_AR: return "Data from AR";
06086         case ID_AC: return "Data from AC";
06087         case ID_LI: return "Data from LI";
06088         case ID_MB: return "Data from MB";
06089         case ID_IM: return "Data from IM";
06090         case ID_LT: return "Data from LT";
06091         case ID_LA: return "Data from LA";
06092         case ID_CA: return "Data from CA";
06093         case ID_KE: return "Data from KE";
06094         case ID_WO: return "Data from WO";
06095         case ID_SCR: return "Data from SCR";
06096         case ID_VF: return "Data from VF";
06097         case ID_TXT : return "Data from TXT";
06098         case ID_SPK: return "Data from SPK";
06099         case ID_SO: return "Data from SO";
06100         case ID_NT: return "Data from NT";
06101         case ID_BR: return "Data from BR";
06102         case ID_PA: return "Data from PA";
06103         case ID_GD: return "Data from GD";
06104         case ID_MC: return "Data from MC";
06105     }
06106     return "Data from Lib Block";
06107     
06108 }
06109 
06110 static BHead *read_data_into_oldnewmap(FileData *fd, BHead *bhead, const char *allocname)
06111 {
06112     bhead = blo_nextbhead(fd, bhead);
06113 
06114     while(bhead && bhead->code==DATA) {
06115         void *data;
06116 #if 0
06117         /* XXX DUMB DEBUGGING OPTION TO GIVE NAMES for guarded malloc errors */
06118         short *sp= fd->filesdna->structs[bhead->SDNAnr];
06119         char *tmp= malloc(100);
06120         allocname = fd->filesdna->types[ sp[0] ];
06121         strcpy(tmp, allocname);
06122         data= read_struct(fd, bhead, tmp);
06123 #else
06124         data= read_struct(fd, bhead, allocname);
06125 #endif
06126         
06127         if (data) {
06128             oldnewmap_insert(fd->datamap, bhead->old, data, 0);
06129         }
06130 
06131         bhead = blo_nextbhead(fd, bhead);
06132     }
06133 
06134     return bhead;
06135 }
06136 
06137 static BHead *read_libblock(FileData *fd, Main *main, BHead *bhead, int flag, ID **id_r)
06138 {
06139     /* this routine reads a libblock and its direct data. Use link functions
06140      * to connect it all
06141      */
06142 
06143     ID *id;
06144     ListBase *lb;
06145     const char *allocname;
06146     
06147     /* read libblock */
06148     id = read_struct(fd, bhead, "lib block");
06149     if (id_r)
06150         *id_r= id;
06151     if (!id)
06152         return blo_nextbhead(fd, bhead);
06153     
06154     oldnewmap_insert(fd->libmap, bhead->old, id, bhead->code);  /* for ID_ID check */
06155     
06156     /* do after read_struct, for dna reconstruct */
06157     if(bhead->code==ID_ID) {
06158         lb= which_libbase(main, GS(id->name));
06159     }
06160     else {
06161         lb= which_libbase(main, bhead->code);
06162     }
06163     
06164     BLI_addtail(lb, id);
06165 
06166     /* clear first 8 bits */
06167     id->flag= (id->flag & 0xFF00) | flag | LIB_NEEDLINK;
06168     id->lib= main->curlib;
06169     if(id->flag & LIB_FAKEUSER) id->us= 1;
06170     else id->us= 0;
06171     id->icon_id = 0;
06172     id->flag &= ~(LIB_ID_RECALC|LIB_ID_RECALC_DATA);
06173 
06174     /* this case cannot be direct_linked: it's just the ID part */
06175     if(bhead->code==ID_ID) {
06176         return blo_nextbhead(fd, bhead);
06177     }
06178 
06179     /* need a name for the mallocN, just for debugging and sane prints on leaks */
06180     allocname= dataname(GS(id->name));
06181     
06182     /* read all data into fd->datamap */
06183     bhead= read_data_into_oldnewmap(fd, bhead, allocname);
06184 
06185     /* init pointers direct data */
06186     switch( GS(id->name) ) {
06187         case ID_WM:
06188             direct_link_windowmanager(fd, (wmWindowManager *)id);
06189             break;
06190         case ID_SCR:
06191             direct_link_screen(fd, (bScreen *)id);
06192             break;
06193         case ID_SCE:
06194             direct_link_scene(fd, (Scene *)id);
06195             break;
06196         case ID_OB:
06197             direct_link_object(fd, (Object *)id);
06198             break;
06199         case ID_ME:
06200             direct_link_mesh(fd, (Mesh *)id);
06201             break;
06202         case ID_CU:
06203             direct_link_curve(fd, (Curve *)id);
06204             break;
06205         case ID_MB:
06206             direct_link_mball(fd, (MetaBall *)id);
06207             break;
06208         case ID_MA:
06209             direct_link_material(fd, (Material *)id);
06210             break;
06211         case ID_TE:
06212             direct_link_texture(fd, (Tex *)id);
06213             break;
06214         case ID_IM:
06215             direct_link_image(fd, (Image *)id);
06216             break;
06217         case ID_LA:
06218             direct_link_lamp(fd, (Lamp *)id);
06219             break;
06220         case ID_VF:
06221             direct_link_vfont(fd, (VFont *)id);
06222             break;
06223         case ID_TXT:
06224             direct_link_text(fd, (Text *)id);
06225             break;
06226         case ID_IP:
06227             direct_link_ipo(fd, (Ipo *)id);
06228             break;
06229         case ID_KE:
06230             direct_link_key(fd, (Key *)id);
06231             break;
06232         case ID_LT:
06233             direct_link_latt(fd, (Lattice *)id);
06234             break;
06235         case ID_WO:
06236             direct_link_world(fd, (World *)id);
06237             break;
06238         case ID_LI:
06239             direct_link_library(fd, (Library *)id, main);
06240             break;
06241         case ID_CA:
06242             direct_link_camera(fd, (Camera *)id);
06243             break;
06244         case ID_SPK:
06245             direct_link_speaker(fd, (Speaker *)id);
06246             break;
06247         case ID_SO:
06248             direct_link_sound(fd, (bSound *)id);
06249             break;
06250         case ID_GR:
06251             direct_link_group(fd, (Group *)id);
06252             break;
06253         case ID_AR:
06254             direct_link_armature(fd, (bArmature*)id);
06255             break;
06256         case ID_AC:
06257             direct_link_action(fd, (bAction*)id);
06258             break;
06259         case ID_NT:
06260             direct_link_nodetree(fd, (bNodeTree*)id);
06261             break;
06262         case ID_BR:
06263             direct_link_brush(fd, (Brush*)id);
06264             break;
06265         case ID_PA:
06266             direct_link_particlesettings(fd, (ParticleSettings*)id);
06267             break;
06268         case ID_SCRIPT:
06269             direct_link_script(fd, (Script*)id);
06270             break;
06271         case ID_GD:
06272             direct_link_gpencil(fd, (bGPdata *)id);
06273             break;
06274         case ID_MC:
06275             direct_link_movieclip(fd, (MovieClip *)id);
06276             break;
06277     }
06278     
06279     /*link direct data of ID properties*/
06280     if (id->properties) {
06281         id->properties = newdataadr(fd, id->properties);
06282         if (id->properties) { /* this case means the data was written incorrectly, it should not happen */
06283             IDP_DirectLinkProperty(id->properties, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
06284         }
06285     }
06286 
06287     oldnewmap_free_unused(fd->datamap);
06288     oldnewmap_clear(fd->datamap);
06289 
06290     return (bhead);
06291 }
06292 
06293 /* note, this has to be kept for reading older files... */
06294 /* also version info is written here */
06295 static BHead *read_global(BlendFileData *bfd, FileData *fd, BHead *bhead)
06296 {
06297     FileGlobal *fg= read_struct(fd, bhead, "Global");
06298     
06299     /* copy to bfd handle */
06300     bfd->main->subversionfile= fg->subversion;
06301     bfd->main->minversionfile= fg->minversion;
06302     bfd->main->minsubversionfile= fg->minsubversion;
06303     bfd->main->revision= fg->revision;
06304     
06305     bfd->winpos= fg->winpos;
06306     bfd->fileflags= fg->fileflags;
06307     bfd->displaymode= fg->displaymode;
06308     bfd->globalf= fg->globalf;
06309     BLI_strncpy(bfd->filename, fg->filename, sizeof(bfd->filename));
06310     
06311     if(G.fileflags & G_FILE_RECOVER)
06312         BLI_strncpy(fd->relabase, fg->filename, sizeof(fd->relabase));
06313     
06314     bfd->curscreen= fg->curscreen;
06315     bfd->curscene= fg->curscene;
06316     
06317     MEM_freeN(fg);
06318 
06319     fd->globalf= bfd->globalf;
06320     fd->fileflags= bfd->fileflags;
06321     
06322     return blo_nextbhead(fd, bhead);
06323 }
06324 
06325 /* note, this has to be kept for reading older files... */
06326 static void link_global(FileData *fd, BlendFileData *bfd)
06327 {
06328     
06329     bfd->curscreen= newlibadr(fd, NULL, bfd->curscreen);
06330     bfd->curscene= newlibadr(fd, NULL, bfd->curscene);
06331     // this happens in files older than 2.35
06332     if(bfd->curscene==NULL) {
06333         if(bfd->curscreen) bfd->curscene= bfd->curscreen->scene;
06334     }
06335 }
06336 
06337 static void vcol_to_fcol(Mesh *me)
06338 {
06339     MFace *mface;
06340     unsigned int *mcol, *mcoln, *mcolmain;
06341     int a;
06342 
06343     if(me->totface==0 || me->mcol==NULL) return;
06344 
06345     mcoln= mcolmain= MEM_mallocN(4*sizeof(int)*me->totface, "mcoln");
06346     mcol = (unsigned int *)me->mcol;
06347     mface= me->mface;
06348     for(a=me->totface; a>0; a--, mface++) {
06349         mcoln[0]= mcol[mface->v1];
06350         mcoln[1]= mcol[mface->v2];
06351         mcoln[2]= mcol[mface->v3];
06352         mcoln[3]= mcol[mface->v4];
06353         mcoln+= 4;
06354     }
06355 
06356     MEM_freeN(me->mcol);
06357     me->mcol= (MCol *)mcolmain;
06358 }
06359 
06360 static int map_223_keybd_code_to_224_keybd_code(int code)
06361 {
06362     switch (code) {
06363         case 312:   return 311; /* F12KEY */
06364         case 159:   return 161; /* PADSLASHKEY */
06365         case 161:   return 150; /* PAD0 */
06366         case 154:   return 151; /* PAD1 */
06367         case 150:   return 152; /* PAD2 */
06368         case 155:   return 153; /* PAD3 */
06369         case 151:   return 154; /* PAD4 */
06370         case 156:   return 155; /* PAD5 */
06371         case 152:   return 156; /* PAD6 */
06372         case 157:   return 157; /* PAD7 */
06373         case 153:   return 158; /* PAD8 */
06374         case 158:   return 159; /* PAD9 */
06375         default: return code;
06376     }
06377 }
06378 
06379 static void do_version_bone_head_tail_237(Bone *bone)
06380 {
06381     Bone *child;
06382     float vec[3];
06383 
06384     /* head */
06385     copy_v3_v3(bone->arm_head, bone->arm_mat[3]);
06386 
06387     /* tail is in current local coord system */
06388     copy_v3_v3(vec, bone->arm_mat[1]);
06389     mul_v3_fl(vec, bone->length);
06390     add_v3_v3v3(bone->arm_tail, bone->arm_head, vec);
06391 
06392     for(child= bone->childbase.first; child; child= child->next)
06393         do_version_bone_head_tail_237(child);
06394 }
06395 
06396 static void bone_version_238(ListBase *lb)
06397 {
06398     Bone *bone;
06399     
06400     for(bone= lb->first; bone; bone= bone->next) {
06401         if(bone->rad_tail==0.0f && bone->rad_head==0.0f) {
06402             bone->rad_head= 0.25f*bone->length;
06403             bone->rad_tail= 0.1f*bone->length;
06404             
06405             bone->dist-= bone->rad_head;
06406             if(bone->dist<=0.0f) bone->dist= 0.0f;
06407         }
06408         bone_version_238(&bone->childbase);
06409     }
06410 }
06411 
06412 static void bone_version_239(ListBase *lb)
06413 {
06414     Bone *bone;
06415     
06416     for(bone= lb->first; bone; bone= bone->next) {
06417         if(bone->layer==0) 
06418             bone->layer= 1;
06419         bone_version_239(&bone->childbase);
06420     }
06421 }
06422 
06423 static void ntree_version_241(bNodeTree *ntree)
06424 {
06425     bNode *node;
06426     
06427     if(ntree->type==NTREE_COMPOSIT) {
06428         for(node= ntree->nodes.first; node; node= node->next) {
06429             if(node->type==CMP_NODE_BLUR) {
06430                 if(node->storage==NULL) {
06431                     NodeBlurData *nbd= MEM_callocN(sizeof(NodeBlurData), "node blur patch");
06432                     nbd->sizex= node->custom1;
06433                     nbd->sizey= node->custom2;
06434                     nbd->filtertype= R_FILTER_QUAD;
06435                     node->storage= nbd;
06436                 }
06437             }
06438             else if(node->type==CMP_NODE_VECBLUR) {
06439                 if(node->storage==NULL) {
06440                     NodeBlurData *nbd= MEM_callocN(sizeof(NodeBlurData), "node blur patch");
06441                     nbd->samples= node->custom1;
06442                     nbd->maxspeed= node->custom2;
06443                     nbd->fac= 1.0f;
06444                     node->storage= nbd;
06445                 }
06446             }
06447         }
06448     }
06449 }
06450 
06451 static void ntree_version_242(bNodeTree *ntree)
06452 {
06453     bNode *node;
06454     
06455     if(ntree->type==NTREE_COMPOSIT) {
06456         for(node= ntree->nodes.first; node; node= node->next) {
06457             if(node->type==CMP_NODE_HUE_SAT) {
06458                 if(node->storage) {
06459                     NodeHueSat *nhs= node->storage;
06460                     if(nhs->val==0.0f) nhs->val= 1.0f;
06461                 }
06462             }
06463         }
06464     }
06465     else if(ntree->type==NTREE_SHADER) {
06466         for(node= ntree->nodes.first; node; node= node->next)
06467             if(node->type == SH_NODE_GEOMETRY && node->storage == NULL)
06468                 node->storage= MEM_callocN(sizeof(NodeGeometry), "NodeGeometry");
06469     }
06470     
06471 }
06472 
06473 
06474 /* somehow, probably importing via python, keyblock adrcodes are not in order */
06475 static void sort_shape_fix(Main *main)
06476 {
06477     Key *key;
06478     KeyBlock *kb;
06479     int sorted= 0;
06480     
06481     while(sorted==0) {
06482         sorted= 1;
06483         for(key= main->key.first; key; key= key->id.next) {
06484             for(kb= key->block.first; kb; kb= kb->next) {
06485                 if(kb->next && kb->adrcode>kb->next->adrcode) {
06486                     KeyBlock *next= kb->next;
06487                     BLI_remlink(&key->block, kb);
06488                     BLI_insertlink(&key->block, next, kb);
06489                     kb= next;
06490                     sorted= 0;
06491                 }
06492             }
06493         }
06494         if(sorted==0) printf("warning, shape keys were sorted incorrect, fixed it!\n");
06495     }
06496 }
06497 
06498 static void customdata_version_242(Mesh *me)
06499 {
06500     CustomDataLayer *layer;
06501     MTFace *mtf;
06502     MCol *mcol;
06503     TFace *tf;
06504     int a, mtfacen, mcoln;
06505 
06506     if (!me->vdata.totlayer) {
06507         CustomData_add_layer(&me->vdata, CD_MVERT, CD_ASSIGN, me->mvert, me->totvert);
06508 
06509         if (me->msticky)
06510             CustomData_add_layer(&me->vdata, CD_MSTICKY, CD_ASSIGN, me->msticky, me->totvert);
06511         if (me->dvert)
06512             CustomData_add_layer(&me->vdata, CD_MDEFORMVERT, CD_ASSIGN, me->dvert, me->totvert);
06513     }
06514 
06515     if (!me->edata.totlayer)
06516         CustomData_add_layer(&me->edata, CD_MEDGE, CD_ASSIGN, me->medge, me->totedge);
06517     
06518     if (!me->fdata.totlayer) {
06519         CustomData_add_layer(&me->fdata, CD_MFACE, CD_ASSIGN, me->mface, me->totface);
06520 
06521         if (me->tface) {
06522             if (me->mcol)
06523                 MEM_freeN(me->mcol);
06524 
06525             me->mcol= CustomData_add_layer(&me->fdata, CD_MCOL, CD_CALLOC, NULL, me->totface);
06526             me->mtface= CustomData_add_layer(&me->fdata, CD_MTFACE, CD_CALLOC, NULL, me->totface);
06527 
06528             mtf= me->mtface;
06529             mcol= me->mcol;
06530             tf= me->tface;
06531 
06532             for (a=0; a < me->totface; a++, mtf++, tf++, mcol+=4) {
06533                 memcpy(mcol, tf->col, sizeof(tf->col));
06534                 memcpy(mtf->uv, tf->uv, sizeof(tf->uv));
06535 
06536                 mtf->flag= tf->flag;
06537                 mtf->unwrap= tf->unwrap;
06538                 mtf->mode= tf->mode;
06539                 mtf->tile= tf->tile;
06540                 mtf->tpage= tf->tpage;
06541                 mtf->transp= tf->transp;
06542             }
06543 
06544             MEM_freeN(me->tface);
06545             me->tface= NULL;
06546         }
06547         else if (me->mcol) {
06548             me->mcol= CustomData_add_layer(&me->fdata, CD_MCOL, CD_ASSIGN, me->mcol, me->totface);
06549         }
06550     }
06551 
06552     if (me->tface) {
06553         MEM_freeN(me->tface);
06554         me->tface= NULL;
06555     }
06556 
06557     for (a=0, mtfacen=0, mcoln=0; a < me->fdata.totlayer; a++) {
06558         layer= &me->fdata.layers[a];
06559 
06560         if (layer->type == CD_MTFACE) {
06561             if (layer->name[0] == 0) {
06562                 if (mtfacen == 0) strcpy(layer->name, "UVMap");
06563                 else BLI_snprintf(layer->name, sizeof(layer->name), "UVMap.%.3d", mtfacen);
06564             }
06565             mtfacen++;
06566         }
06567         else if (layer->type == CD_MCOL) {
06568             if (layer->name[0] == 0) {
06569                 if (mcoln == 0) strcpy(layer->name, "Col");
06570                 else BLI_snprintf(layer->name, sizeof(layer->name), "Col.%.3d", mcoln);
06571             }
06572             mcoln++;
06573         }
06574     }
06575 
06576     mesh_update_customdata_pointers(me);
06577 }
06578 
06579 /*only copy render texface layer from active*/
06580 static void customdata_version_243(Mesh *me)
06581 {
06582     CustomDataLayer *layer;
06583     int a;
06584 
06585     for (a=0; a < me->fdata.totlayer; a++) {
06586         layer= &me->fdata.layers[a];
06587         layer->active_rnd = layer->active;
06588     }
06589 }
06590 
06591 /* struct NodeImageAnim moved to ImageUser, and we make it default available */
06592 static void do_version_ntree_242_2(bNodeTree *ntree)
06593 {
06594     bNode *node;
06595     
06596     if(ntree->type==NTREE_COMPOSIT) {
06597         for(node= ntree->nodes.first; node; node= node->next) {
06598             if(ELEM3(node->type, CMP_NODE_IMAGE, CMP_NODE_VIEWER, CMP_NODE_SPLITVIEWER)) {
06599                 /* only image had storage */
06600                 if(node->storage) {
06601                     NodeImageAnim *nia= node->storage;
06602                     ImageUser *iuser= MEM_callocN(sizeof(ImageUser), "ima user node");
06603 
06604                     iuser->frames= nia->frames;
06605                     iuser->sfra= nia->sfra;
06606                     iuser->offset= nia->nr-1;
06607                     iuser->cycl= nia->cyclic;
06608                     iuser->fie_ima= 2;
06609                     iuser->ok= 1;
06610                     
06611                     node->storage= iuser;
06612                     MEM_freeN(nia);
06613                 }
06614                 else {
06615                     ImageUser *iuser= node->storage= MEM_callocN(sizeof(ImageUser), "node image user");
06616                     iuser->sfra= 1;
06617                     iuser->fie_ima= 2;
06618                     iuser->ok= 1;
06619                 }
06620             }
06621         }
06622     }
06623 }
06624 
06625 static void ntree_version_245(FileData *fd, Library *lib, bNodeTree *ntree)
06626 {
06627     bNode *node;
06628     NodeTwoFloats *ntf;
06629     ID *nodeid;
06630     Image *image;
06631     ImageUser *iuser;
06632 
06633     if(ntree->type==NTREE_COMPOSIT) {
06634         for(node= ntree->nodes.first; node; node= node->next) {
06635             if(node->type == CMP_NODE_ALPHAOVER) {
06636                 if(!node->storage) {
06637                     ntf= MEM_callocN(sizeof(NodeTwoFloats), "NodeTwoFloats");
06638                     node->storage= ntf;
06639                     if(node->custom1)
06640                         ntf->x= 1.0f;
06641                 }
06642             }
06643             
06644             /* fix for temporary flag changes during 245 cycle */
06645             nodeid= newlibadr(fd, lib, node->id);
06646             if(node->storage && nodeid && GS(nodeid->name) == ID_IM) {
06647                 image= (Image*)nodeid;
06648                 iuser= node->storage;
06649                 if(iuser->flag & IMA_OLD_PREMUL) {
06650                     iuser->flag &= ~IMA_OLD_PREMUL;
06651                     iuser->flag |= IMA_DO_PREMUL;
06652                 }
06653                 if(iuser->flag & IMA_DO_PREMUL) {
06654                     image->flag &= ~IMA_OLD_PREMUL;
06655                     image->flag |= IMA_DO_PREMUL;
06656                 }
06657             }
06658         }
06659     }
06660 }
06661 
06662 static void idproperties_fix_groups_lengths_recurse(IDProperty *prop)
06663 {
06664     IDProperty *loop;
06665     int i;
06666     
06667     for (loop=prop->data.group.first, i=0; loop; loop=loop->next, i++) {
06668         if (loop->type == IDP_GROUP) idproperties_fix_groups_lengths_recurse(loop);
06669     }
06670     
06671     if (prop->len != i) {
06672         printf("Found and fixed bad id property group length.\n");
06673         prop->len = i;
06674     }
06675 }
06676 
06677 static void idproperties_fix_group_lengths(ListBase idlist)
06678 {
06679     ID *id;
06680     
06681     for (id=idlist.first; id; id=id->next) {
06682         if (id->properties) {
06683             idproperties_fix_groups_lengths_recurse(id->properties);
06684         }
06685     }
06686 }
06687 
06688 static void alphasort_version_246(FileData *fd, Library *lib, Mesh *me)
06689 {
06690     Material *ma;
06691     MFace *mf;
06692     MTFace *tf;
06693     int a, b, texalpha;
06694 
06695     /* verify we have a tface layer */
06696     for(b=0; b<me->fdata.totlayer; b++)
06697         if(me->fdata.layers[b].type == CD_MTFACE)
06698             break;
06699     
06700     if(b == me->fdata.totlayer)
06701         return;
06702 
06703     /* if we do, set alpha sort if the game engine did it before */
06704     for(a=0, mf=me->mface; a<me->totface; a++, mf++) {
06705         if(mf->mat_nr < me->totcol) {
06706             ma= newlibadr(fd, lib, me->mat[mf->mat_nr]);
06707             texalpha = 0;
06708 
06709             /* we can't read from this if it comes from a library,
06710              * because direct_link might not have happened on it,
06711              * so ma->mtex is not pointing to valid memory yet */
06712             if(ma && ma->id.lib)
06713                 ma= NULL;
06714 
06715             for(b=0; ma && b<MAX_MTEX; b++)
06716                 if(ma->mtex && ma->mtex[b] && ma->mtex[b]->mapto & MAP_ALPHA)
06717                     texalpha = 1;
06718         }
06719         else {
06720             ma= NULL;
06721             texalpha = 0;
06722         }
06723 
06724         for(b=0; b<me->fdata.totlayer; b++) {
06725             if(me->fdata.layers[b].type == CD_MTFACE) {
06726                 tf = ((MTFace*)me->fdata.layers[b].data) + a;
06727 
06728                 tf->mode &= ~TF_ALPHASORT;
06729                 if(ma && (ma->mode & MA_ZTRANSP))
06730                     if(ELEM(tf->transp, TF_ALPHA, TF_ADD) || (texalpha && (tf->transp != TF_CLIP)))
06731                         tf->mode |= TF_ALPHASORT;
06732             }
06733         }
06734     }
06735 }
06736 
06737 /* 2.50 patch */
06738 static void area_add_header_region(ScrArea *sa, ListBase *lb)
06739 {
06740     ARegion *ar= MEM_callocN(sizeof(ARegion), "area region from do_versions");
06741     
06742     BLI_addtail(lb, ar);
06743     ar->regiontype= RGN_TYPE_HEADER;
06744     if(sa->headertype==HEADERDOWN)
06745         ar->alignment= RGN_ALIGN_BOTTOM;
06746     else
06747         ar->alignment= RGN_ALIGN_TOP;
06748     
06749     /* initialise view2d data for header region, to allow panning */
06750     /* is copy from ui_view2d.c */
06751     ar->v2d.keepzoom = (V2D_LOCKZOOM_X|V2D_LOCKZOOM_Y|V2D_LIMITZOOM|V2D_KEEPASPECT);
06752     ar->v2d.keepofs = V2D_LOCKOFS_Y;
06753     ar->v2d.keeptot = V2D_KEEPTOT_STRICT; 
06754     ar->v2d.align = V2D_ALIGN_NO_NEG_X|V2D_ALIGN_NO_NEG_Y;
06755     ar->v2d.flag = (V2D_PIXELOFS_X|V2D_PIXELOFS_Y);
06756 }
06757 
06758 static void sequencer_init_preview_region(ARegion* ar)
06759 {
06760     // XXX a bit ugly still, copied from space_sequencer
06761     /* NOTE: if you change values here, also change them in space_sequencer.c, sequencer_new */
06762     ar->regiontype= RGN_TYPE_PREVIEW;
06763     ar->alignment= RGN_ALIGN_TOP;
06764     ar->flag |= RGN_FLAG_HIDDEN;
06765     ar->v2d.keepzoom= V2D_KEEPASPECT | V2D_KEEPZOOM;
06766     ar->v2d.minzoom= 0.00001f;
06767     ar->v2d.maxzoom= 100000.0f;
06768     ar->v2d.tot.xmin= -960.0f; /* 1920 width centered */
06769     ar->v2d.tot.ymin= -540.0f; /* 1080 height centered */
06770     ar->v2d.tot.xmax= 960.0f;
06771     ar->v2d.tot.ymax= 540.0f;
06772     ar->v2d.min[0]= 0.0f;
06773     ar->v2d.min[1]= 0.0f;
06774     ar->v2d.max[0]= 12000.0f;
06775     ar->v2d.max[1]= 12000.0f;
06776     ar->v2d.cur= ar->v2d.tot;
06777     ar->v2d.align= V2D_ALIGN_FREE; // (V2D_ALIGN_NO_NEG_X|V2D_ALIGN_NO_NEG_Y);
06778     ar->v2d.keeptot= V2D_KEEPTOT_FREE;
06779 }
06780 
06781 /* 2.50 patch */
06782 static void area_add_window_regions(ScrArea *sa, SpaceLink *sl, ListBase *lb)
06783 {
06784     ARegion *ar;
06785     ARegion *ar_main;
06786 
06787     if(sl) {
06788         /* first channels for ipo action nla... */
06789         switch(sl->spacetype) {
06790             case SPACE_IPO:
06791                 ar= MEM_callocN(sizeof(ARegion), "area region from do_versions");
06792                 BLI_addtail(lb, ar);
06793                 ar->regiontype= RGN_TYPE_CHANNELS;
06794                 ar->alignment= RGN_ALIGN_LEFT; 
06795                 ar->v2d.scroll= (V2D_SCROLL_RIGHT|V2D_SCROLL_BOTTOM);
06796                 
06797                     // for some reason, this doesn't seem to go auto like for NLA...
06798                 ar= MEM_callocN(sizeof(ARegion), "area region from do_versions");
06799                 BLI_addtail(lb, ar);
06800                 ar->regiontype= RGN_TYPE_UI;
06801                 ar->alignment= RGN_ALIGN_RIGHT;
06802                 ar->v2d.scroll= V2D_SCROLL_RIGHT;
06803                 ar->v2d.flag = RGN_FLAG_HIDDEN;
06804                 break;
06805                 
06806             case SPACE_ACTION:
06807                 ar= MEM_callocN(sizeof(ARegion), "area region from do_versions");
06808                 BLI_addtail(lb, ar);
06809                 ar->regiontype= RGN_TYPE_CHANNELS;
06810                 ar->alignment= RGN_ALIGN_LEFT;
06811                 ar->v2d.scroll= V2D_SCROLL_BOTTOM;
06812                 ar->v2d.flag = V2D_VIEWSYNC_AREA_VERTICAL;
06813                 break;
06814                 
06815             case SPACE_NLA:
06816                 ar= MEM_callocN(sizeof(ARegion), "area region from do_versions");
06817                 BLI_addtail(lb, ar);
06818                 ar->regiontype= RGN_TYPE_CHANNELS;
06819                 ar->alignment= RGN_ALIGN_LEFT;
06820                 ar->v2d.scroll= V2D_SCROLL_BOTTOM;
06821                 ar->v2d.flag = V2D_VIEWSYNC_AREA_VERTICAL;
06822                 
06823                     // for some reason, some files still don't get this auto
06824                 ar= MEM_callocN(sizeof(ARegion), "area region from do_versions");
06825                 BLI_addtail(lb, ar);
06826                 ar->regiontype= RGN_TYPE_UI;
06827                 ar->alignment= RGN_ALIGN_RIGHT;
06828                 ar->v2d.scroll= V2D_SCROLL_RIGHT;
06829                 ar->v2d.flag = RGN_FLAG_HIDDEN;
06830                 break;
06831                 
06832             case SPACE_NODE:
06833                 ar= MEM_callocN(sizeof(ARegion), "nodetree area for node");
06834                 BLI_addtail(lb, ar);
06835                 ar->regiontype= RGN_TYPE_UI;
06836                 ar->alignment= RGN_ALIGN_LEFT;
06837                 ar->v2d.scroll = (V2D_SCROLL_RIGHT|V2D_SCROLL_BOTTOM);
06838                 ar->v2d.flag = V2D_VIEWSYNC_AREA_VERTICAL;
06839                 /* temporarily hide it */
06840                 ar->flag = RGN_FLAG_HIDDEN;
06841                 break;
06842             case SPACE_FILE:
06843                 ar= MEM_callocN(sizeof(ARegion), "nodetree area for node");
06844                 BLI_addtail(lb, ar);
06845                 ar->regiontype= RGN_TYPE_CHANNELS;
06846                 ar->alignment= RGN_ALIGN_LEFT;
06847 
06848                 ar= MEM_callocN(sizeof(ARegion), "ui area for file");
06849                 BLI_addtail(lb, ar);
06850                 ar->regiontype= RGN_TYPE_UI;
06851                 ar->alignment= RGN_ALIGN_TOP;
06852                 break;
06853             case SPACE_SEQ:
06854                 ar_main = (ARegion*)lb->first;
06855                 for (; ar_main; ar_main = ar_main->next) {
06856                     if (ar_main->regiontype == RGN_TYPE_WINDOW)
06857                         break;
06858                 }
06859                 ar= MEM_callocN(sizeof(ARegion), "preview area for sequencer");
06860                 BLI_insertlinkbefore(lb, ar_main, ar);
06861                 sequencer_init_preview_region(ar);
06862                 break;
06863             case SPACE_VIEW3D:
06864                 /* toolbar */
06865                 ar= MEM_callocN(sizeof(ARegion), "toolbar for view3d");
06866                 
06867                 BLI_addtail(lb, ar);
06868                 ar->regiontype= RGN_TYPE_TOOLS;
06869                 ar->alignment= RGN_ALIGN_LEFT;
06870                 ar->flag = RGN_FLAG_HIDDEN;
06871                 
06872                 /* tool properties */
06873                 ar= MEM_callocN(sizeof(ARegion), "tool properties for view3d");
06874                 
06875                 BLI_addtail(lb, ar);
06876                 ar->regiontype= RGN_TYPE_TOOL_PROPS;
06877                 ar->alignment= RGN_ALIGN_BOTTOM|RGN_SPLIT_PREV;
06878                 ar->flag = RGN_FLAG_HIDDEN;
06879                 
06880                 /* buttons/list view */
06881                 ar= MEM_callocN(sizeof(ARegion), "buttons for view3d");
06882                 
06883                 BLI_addtail(lb, ar);
06884                 ar->regiontype= RGN_TYPE_UI;
06885                 ar->alignment= RGN_ALIGN_RIGHT;
06886                 ar->flag = RGN_FLAG_HIDDEN;
06887 #if 0
06888             case SPACE_BUTS:
06889                 /* context UI region */
06890                 ar= MEM_callocN(sizeof(ARegion), "area region from do_versions");
06891                 BLI_addtail(lb, ar);
06892                 ar->regiontype= RGN_TYPE_UI;
06893                 ar->alignment= RGN_ALIGN_RIGHT;
06894                 
06895                 break;
06896 #endif
06897         }
06898     }
06899 
06900     /* main region */
06901     ar= MEM_callocN(sizeof(ARegion), "area region from do_versions");
06902     
06903     BLI_addtail(lb, ar);
06904     ar->winrct= sa->totrct;
06905     
06906     ar->regiontype= RGN_TYPE_WINDOW;
06907     
06908     if(sl) {
06909         /* if active spacetype has view2d data, copy that over to main region */
06910         /* and we split view3d */
06911         switch(sl->spacetype) {
06912             case SPACE_VIEW3D:
06913                 view3d_split_250((View3D *)sl, lb);
06914                 break;      
06915                         
06916             case SPACE_OUTLINER:
06917             {
06918                 SpaceOops *soops= (SpaceOops *)sl;
06919                 
06920                 memcpy(&ar->v2d, &soops->v2d, sizeof(View2D));
06921                 
06922                 ar->v2d.scroll &= ~V2D_SCROLL_LEFT;
06923                 ar->v2d.scroll |= (V2D_SCROLL_RIGHT|V2D_SCROLL_BOTTOM_O);
06924                 ar->v2d.align = (V2D_ALIGN_NO_NEG_X|V2D_ALIGN_NO_POS_Y);
06925                 ar->v2d.keepzoom |= (V2D_LOCKZOOM_X|V2D_LOCKZOOM_Y|V2D_KEEPASPECT);
06926                 ar->v2d.keeptot = V2D_KEEPTOT_STRICT;
06927                 ar->v2d.minzoom= ar->v2d.maxzoom= 1.0f;
06928                 //ar->v2d.flag |= V2D_IS_INITIALISED;
06929             }
06930                 break;
06931             case SPACE_TIME:
06932             {
06933                 SpaceTime *stime= (SpaceTime *)sl;
06934                 memcpy(&ar->v2d, &stime->v2d, sizeof(View2D));
06935                 
06936                 ar->v2d.scroll |= (V2D_SCROLL_BOTTOM|V2D_SCROLL_SCALE_HORIZONTAL);
06937                 ar->v2d.align |= V2D_ALIGN_NO_NEG_Y;
06938                 ar->v2d.keepofs |= V2D_LOCKOFS_Y;
06939                 ar->v2d.keepzoom |= V2D_LOCKZOOM_Y;
06940                 ar->v2d.tot.ymin= ar->v2d.cur.ymin= -10.0;
06941                 ar->v2d.min[1]= ar->v2d.max[1]= 20.0;
06942             }
06943                 break;
06944             case SPACE_IPO:
06945             {
06946                 SpaceIpo *sipo= (SpaceIpo *)sl;
06947                 memcpy(&ar->v2d, &sipo->v2d, sizeof(View2D));
06948                 
06949                 /* init mainarea view2d */
06950                 ar->v2d.scroll |= (V2D_SCROLL_BOTTOM|V2D_SCROLL_SCALE_HORIZONTAL);
06951                 ar->v2d.scroll |= (V2D_SCROLL_LEFT|V2D_SCROLL_SCALE_VERTICAL);
06952                 
06953                 ar->v2d.min[0]= FLT_MIN;
06954                 ar->v2d.min[1]= FLT_MIN;
06955                 
06956                 ar->v2d.max[0]= MAXFRAMEF;
06957                 ar->v2d.max[1]= FLT_MAX;
06958                 
06959                 //ar->v2d.flag |= V2D_IS_INITIALISED;
06960                 break;
06961             }
06962             case SPACE_NLA:
06963             {
06964                 SpaceNla *snla= (SpaceNla *)sl;
06965                 memcpy(&ar->v2d, &snla->v2d, sizeof(View2D));
06966                 
06967                 ar->v2d.tot.ymin= (float)(-sa->winy)/3.0f;
06968                 ar->v2d.tot.ymax= 0.0f;
06969                 
06970                 ar->v2d.scroll |= (V2D_SCROLL_BOTTOM|V2D_SCROLL_SCALE_HORIZONTAL);
06971                 ar->v2d.scroll |= (V2D_SCROLL_RIGHT);
06972                 ar->v2d.align = V2D_ALIGN_NO_POS_Y;
06973                 ar->v2d.flag |= V2D_VIEWSYNC_AREA_VERTICAL;
06974                 break;
06975             }
06976             case SPACE_ACTION:
06977             {
06978                 SpaceAction *saction= (SpaceAction *)sl;
06979                 
06980                 /* we totally reinit the view for the Action Editor, as some old instances had some weird cruft set */
06981                 ar->v2d.tot.xmin= -20.0f;
06982                 ar->v2d.tot.ymin= (float)(-sa->winy)/3.0f;
06983                 ar->v2d.tot.xmax= (float)((sa->winx > 120)? (sa->winx) : 120);
06984                 ar->v2d.tot.ymax= 0.0f;
06985                 
06986                 ar->v2d.cur= ar->v2d.tot;
06987                 
06988                 ar->v2d.min[0]= 0.0f;
06989                 ar->v2d.min[1]= 0.0f;
06990                 
06991                 ar->v2d.max[0]= MAXFRAMEF;
06992                 ar->v2d.max[1]= FLT_MAX;
06993 
06994                 ar->v2d.minzoom= 0.01f;
06995                 ar->v2d.maxzoom= 50;
06996                 ar->v2d.scroll = (V2D_SCROLL_BOTTOM|V2D_SCROLL_SCALE_HORIZONTAL);
06997                 ar->v2d.scroll |= (V2D_SCROLL_RIGHT);
06998                 ar->v2d.keepzoom= V2D_LOCKZOOM_Y;
06999                 ar->v2d.align= V2D_ALIGN_NO_POS_Y;
07000                 ar->v2d.flag = V2D_VIEWSYNC_AREA_VERTICAL;
07001                 
07002                 /* for old files with ShapeKey editors open + an action set, clear the action as 
07003                  * it doesn't make sense in the new system (i.e. violates concept that ShapeKey edit
07004                  * only shows ShapeKey-rooted actions only)
07005                  */
07006                 if (saction->mode == SACTCONT_SHAPEKEY)
07007                     saction->action = NULL;
07008                 break;
07009             }
07010             case SPACE_SEQ:
07011             {
07012                 SpaceSeq *sseq= (SpaceSeq *)sl;
07013                 memcpy(&ar->v2d, &sseq->v2d, sizeof(View2D));
07014                 
07015                 ar->v2d.scroll |= (V2D_SCROLL_BOTTOM|V2D_SCROLL_SCALE_HORIZONTAL);
07016                 ar->v2d.scroll |= (V2D_SCROLL_LEFT|V2D_SCROLL_SCALE_VERTICAL);
07017                 ar->v2d.align= V2D_ALIGN_NO_NEG_Y;
07018                 ar->v2d.flag |= V2D_IS_INITIALISED;
07019                 break;
07020             }
07021             case SPACE_NODE:
07022             {
07023                 SpaceNode *snode= (SpaceNode *)sl;
07024                 memcpy(&ar->v2d, &snode->v2d, sizeof(View2D));
07025                 
07026                 ar->v2d.scroll= (V2D_SCROLL_RIGHT|V2D_SCROLL_BOTTOM);
07027                 ar->v2d.keepzoom= V2D_LIMITZOOM|V2D_KEEPASPECT;
07028                 break;
07029             }
07030             case SPACE_BUTS:
07031             {
07032                 SpaceButs *sbuts= (SpaceButs *)sl;
07033                 memcpy(&ar->v2d, &sbuts->v2d, sizeof(View2D));
07034                 
07035                 ar->v2d.scroll |= (V2D_SCROLL_RIGHT|V2D_SCROLL_BOTTOM); 
07036                 break;
07037             }
07038             case SPACE_FILE:
07039              {
07040                 // SpaceFile *sfile= (SpaceFile *)sl;
07041                 ar->v2d.tot.xmin = ar->v2d.tot.ymin = 0;
07042                 ar->v2d.tot.xmax = ar->winx;
07043                 ar->v2d.tot.ymax = ar->winy;
07044                 ar->v2d.cur = ar->v2d.tot;
07045                 ar->regiontype= RGN_TYPE_WINDOW;
07046                 ar->v2d.scroll = (V2D_SCROLL_RIGHT|V2D_SCROLL_BOTTOM_O);
07047                 ar->v2d.align = (V2D_ALIGN_NO_NEG_X|V2D_ALIGN_NO_POS_Y);
07048                 ar->v2d.keepzoom = (V2D_LOCKZOOM_X|V2D_LOCKZOOM_Y|V2D_LIMITZOOM|V2D_KEEPASPECT);
07049                 break;
07050             }
07051             case SPACE_TEXT:
07052             {
07053                 SpaceText *st= (SpaceText *)sl;
07054                 st->flags |= ST_FIND_WRAP;
07055             }
07056                 //case SPACE_XXX: // FIXME... add other ones
07057                 //  memcpy(&ar->v2d, &((SpaceXxx *)sl)->v2d, sizeof(View2D));
07058                 //  break;
07059         }
07060     }
07061 }
07062 
07063 static void do_versions_windowmanager_2_50(bScreen *screen)
07064 {
07065     ScrArea *sa;
07066     SpaceLink *sl;
07067     
07068     /* add regions */
07069     for(sa= screen->areabase.first; sa; sa= sa->next) {
07070         
07071         /* we keep headertype variable to convert old files only */
07072         if(sa->headertype)
07073             area_add_header_region(sa, &sa->regionbase);
07074         
07075         area_add_window_regions(sa, sa->spacedata.first, &sa->regionbase);
07076         
07077         /* space imageselect is deprecated */
07078         for(sl= sa->spacedata.first; sl; sl= sl->next) {
07079             if(sl->spacetype==SPACE_IMASEL)
07080                 sl->spacetype= SPACE_EMPTY; /* spacedata then matches */
07081         }
07082         
07083         /* space sound is deprecated */
07084         for(sl= sa->spacedata.first; sl; sl= sl->next) {
07085             if(sl->spacetype==SPACE_SOUND)
07086                 sl->spacetype= SPACE_EMPTY; /* spacedata then matches */
07087         }
07088         
07089         /* it seems to be possible in 2.5 to have this saved, filewindow probably */
07090         sa->butspacetype= sa->spacetype;
07091         
07092         /* pushed back spaces also need regions! */
07093         if(sa->spacedata.first) {
07094             sl= sa->spacedata.first;
07095             for(sl= sl->next; sl; sl= sl->next) {
07096                 if(sa->headertype)
07097                     area_add_header_region(sa, &sl->regionbase);
07098                 area_add_window_regions(sa, sl, &sl->regionbase);
07099             }
07100         }
07101     }
07102 }
07103 
07104 static void versions_gpencil_add_main(ListBase *lb, ID *id, const char *name)
07105 {
07106     
07107     BLI_addtail(lb, id);
07108     id->us= 1;
07109     id->flag= LIB_FAKEUSER;
07110     *( (short *)id->name )= ID_GD;
07111     
07112     new_id(lb, id, name);
07113     /* alphabetic insterion: is in new_id */
07114     
07115     if(G.f & G_DEBUG)
07116         printf("Converted GPencil to ID: %s\n", id->name+2);
07117 }
07118 
07119 static void do_versions_gpencil_2_50(Main *main, bScreen *screen)
07120 {
07121     ScrArea *sa;
07122     SpaceLink *sl;
07123     
07124     /* add regions */
07125     for(sa= screen->areabase.first; sa; sa= sa->next) {
07126         for(sl= sa->spacedata.first; sl; sl= sl->next) {
07127             if (sl->spacetype==SPACE_VIEW3D) {
07128                 View3D *v3d= (View3D*) sl;
07129                 if(v3d->gpd) {
07130                     versions_gpencil_add_main(&main->gpencil, (ID *)v3d->gpd, "GPencil View3D");
07131                     v3d->gpd= NULL;
07132                 }
07133             }
07134             else if (sl->spacetype==SPACE_NODE) {
07135                 SpaceNode *snode= (SpaceNode *)sl;
07136                 if(snode->gpd) {
07137                     versions_gpencil_add_main(&main->gpencil, (ID *)snode->gpd, "GPencil Node");
07138                     snode->gpd= NULL;
07139                 }
07140             }
07141             else if (sl->spacetype==SPACE_SEQ) {
07142                 SpaceSeq *sseq= (SpaceSeq *)sl;
07143                 if(sseq->gpd) {
07144                     versions_gpencil_add_main(&main->gpencil, (ID *)sseq->gpd, "GPencil Node");
07145                     sseq->gpd= NULL;
07146                 }
07147             }
07148             else if (sl->spacetype==SPACE_IMAGE) {
07149                 SpaceImage *sima= (SpaceImage *)sl;
07150 #if 0           /* see comment on r28002 */
07151                 if(sima->gpd) {
07152                     versions_gpencil_add_main(&main->gpencil, (ID *)sima->gpd, "GPencil Image");
07153                     sima->gpd= NULL;
07154                 }
07155 #else
07156                 sima->gpd= NULL;
07157 #endif
07158             }
07159         }
07160     }       
07161 }
07162 
07163 /* deprecated, only keep this for readfile.c */
07164 static PartEff *do_version_give_parteff_245(Object *ob)
07165 {
07166     PartEff *paf;
07167 
07168     paf= ob->effect.first;
07169     while(paf) {
07170         if(paf->type==EFF_PARTICLE) return paf;
07171         paf= paf->next;
07172     }
07173     return NULL;
07174 }
07175 static void do_version_free_effect_245(Effect *eff)
07176 {
07177     PartEff *paf;
07178 
07179     if(eff->type==EFF_PARTICLE) {
07180         paf= (PartEff *)eff;
07181         if(paf->keys) MEM_freeN(paf->keys);
07182     }
07183     MEM_freeN(eff);
07184 }
07185 static void do_version_free_effects_245(ListBase *lb)
07186 {
07187     Effect *eff;
07188 
07189     eff= lb->first;
07190     while(eff) {
07191         BLI_remlink(lb, eff);
07192         do_version_free_effect_245(eff);
07193         eff= lb->first;
07194     }
07195 }
07196 
07197 static void do_version_mtex_factor_2_50(MTex **mtex_array, short idtype)
07198 {
07199     MTex *mtex;
07200     float varfac, colfac;
07201     int a, neg;
07202 
07203     if(!mtex_array)
07204         return;
07205 
07206     for(a=0; a<MAX_MTEX; a++) {
07207         if(mtex_array[a]) {
07208             mtex= mtex_array[a];
07209 
07210             neg= mtex->maptoneg;
07211             varfac= mtex->varfac;
07212             colfac= mtex->colfac;
07213 
07214             if(neg & MAP_DISP) mtex->dispfac= -mtex->dispfac;
07215             if(neg & MAP_NORM) mtex->norfac= -mtex->norfac;
07216             if(neg & MAP_WARP) mtex->warpfac= -mtex->warpfac;
07217 
07218             mtex->colspecfac= (neg & MAP_COLSPEC)? -colfac: colfac;
07219             mtex->mirrfac= (neg & MAP_COLMIR)? -colfac: colfac;
07220             mtex->alphafac= (neg & MAP_ALPHA)? -varfac: varfac;
07221             mtex->difffac= (neg & MAP_REF)? -varfac: varfac;
07222             mtex->specfac= (neg & MAP_SPEC)? -varfac: varfac;
07223             mtex->emitfac= (neg & MAP_EMIT)? -varfac: varfac;
07224             mtex->hardfac= (neg & MAP_HAR)? -varfac: varfac;
07225             mtex->raymirrfac= (neg & MAP_RAYMIRR)? -varfac: varfac;
07226             mtex->translfac= (neg & MAP_TRANSLU)? -varfac: varfac;
07227             mtex->ambfac= (neg & MAP_AMB)? -varfac: varfac;
07228             mtex->colemitfac= (neg & MAP_EMISSION_COL)? -colfac: colfac;
07229             mtex->colreflfac= (neg & MAP_REFLECTION_COL)? -colfac: colfac;
07230             mtex->coltransfac= (neg & MAP_TRANSMISSION_COL)? -colfac: colfac;
07231             mtex->densfac= (neg & MAP_DENSITY)? -varfac: varfac;
07232             mtex->scatterfac= (neg & MAP_SCATTERING)? -varfac: varfac;
07233             mtex->reflfac= (neg & MAP_REFLECTION)? -varfac: varfac;
07234 
07235             mtex->timefac= (neg & MAP_PA_TIME)? -varfac: varfac;
07236             mtex->lengthfac= (neg & MAP_PA_LENGTH)? -varfac: varfac;
07237             mtex->clumpfac= (neg & MAP_PA_CLUMP)? -varfac: varfac;
07238             mtex->kinkfac= (neg & MAP_PA_KINK)? -varfac: varfac;
07239             mtex->roughfac= (neg & MAP_PA_ROUGH)? -varfac: varfac;
07240             mtex->padensfac= (neg & MAP_PA_DENS)? -varfac: varfac;
07241             mtex->lifefac= (neg & MAP_PA_LIFE)? -varfac: varfac;
07242             mtex->sizefac= (neg & MAP_PA_SIZE)? -varfac: varfac;
07243             mtex->ivelfac= (neg & MAP_PA_IVEL)? -varfac: varfac;
07244 
07245             mtex->shadowfac= (neg & LAMAP_SHAD)? -colfac: colfac;
07246 
07247             mtex->zenupfac= (neg & WOMAP_ZENUP)? -colfac: colfac;
07248             mtex->zendownfac= (neg & WOMAP_ZENDOWN)? -colfac: colfac;
07249             mtex->blendfac= (neg & WOMAP_BLEND)? -varfac: varfac;
07250 
07251             if(idtype == ID_MA)
07252                 mtex->colfac= (neg & MAP_COL)? -colfac: colfac;
07253             else if(idtype == ID_LA)
07254                 mtex->colfac= (neg & LAMAP_COL)? -colfac: colfac;
07255             else if(idtype == ID_WO)
07256                 mtex->colfac= (neg & WOMAP_HORIZ)? -colfac: colfac;
07257         }
07258     }
07259 }
07260 
07261 static void do_version_mdef_250(Main *main)
07262 {
07263     Object *ob;
07264     ModifierData *md;
07265     MeshDeformModifierData *mmd;
07266 
07267     for(ob= main->object.first; ob; ob=ob->id.next) {
07268         for(md=ob->modifiers.first; md; md=md->next) {
07269             if(md->type == eModifierType_MeshDeform) {
07270                 mmd= (MeshDeformModifierData*)md;
07271 
07272                 if(mmd->bindcos) {
07273                     /* make bindcos NULL in order to trick older versions
07274                        into thinking that the mesh was not bound yet */
07275                     mmd->bindcagecos= mmd->bindcos;
07276                     mmd->bindcos= NULL;
07277 
07278                     modifier_mdef_compact_influences(md);
07279                 }
07280             }
07281         }
07282     }
07283 }
07284 
07285 static void do_version_constraints_radians_degrees_250(ListBase *lb)
07286 {
07287     bConstraint *con;
07288 
07289     for (con=lb->first; con; con=con->next) {
07290         if(con->type==CONSTRAINT_TYPE_RIGIDBODYJOINT) {
07291             bRigidBodyJointConstraint *data = con->data;
07292             data->axX *= (float)(M_PI/180.0);
07293             data->axY *= (float)(M_PI/180.0);
07294             data->axZ *= (float)(M_PI/180.0);
07295         }
07296         else if(con->type==CONSTRAINT_TYPE_KINEMATIC) {
07297             bKinematicConstraint *data = con->data;
07298             data->poleangle *= (float)(M_PI/180.0);
07299         }
07300         else if(con->type==CONSTRAINT_TYPE_ROTLIMIT) {
07301             bRotLimitConstraint *data = con->data;
07302 
07303             data->xmin *= (float)(M_PI/180.0);
07304             data->xmax *= (float)(M_PI/180.0);
07305             data->ymin *= (float)(M_PI/180.0);
07306             data->ymax *= (float)(M_PI/180.0);
07307             data->zmin *= (float)(M_PI/180.0);
07308             data->zmax *= (float)(M_PI/180.0);
07309         }
07310     }
07311 }
07312 
07313 /* NOTE: this version patch is intended for versions < 2.52.2, but was initially introduced in 2.27 already */
07314 static void do_version_old_trackto_to_constraints(Object *ob)
07315 {
07316     /* create new trackto constraint from the relationship */
07317     if (ob->track)
07318     {
07319         bConstraint *con= add_ob_constraint(ob, "AutoTrack", CONSTRAINT_TYPE_TRACKTO);
07320         bTrackToConstraint *data = con->data;
07321         
07322         /* copy tracking settings from the object */
07323         data->tar = ob->track;
07324         data->reserved1 = ob->trackflag;
07325         data->reserved2 = ob->upflag;
07326     }
07327     
07328     /* clear old track setting */
07329     ob->track = NULL;
07330 }
07331 
07332 static void do_versions_seq_unique_name_all_strips(
07333     Scene * sce, ListBase *seqbasep)
07334 {
07335     Sequence * seq = seqbasep->first;
07336 
07337     while(seq) {
07338         seqbase_unique_name_recursive(&sce->ed->seqbase, seq);
07339         if (seq->seqbase.first) {
07340             do_versions_seq_unique_name_all_strips(
07341                 sce, &seq->seqbase);
07342         }
07343         seq=seq->next;
07344     }
07345 }
07346 
07347 
07348 static void do_version_bone_roll_256(Bone *bone)
07349 {
07350     Bone *child;
07351     float submat[3][3];
07352     
07353     copy_m3_m4(submat, bone->arm_mat);
07354     mat3_to_vec_roll(submat, NULL, &bone->arm_roll);
07355     
07356     for(child = bone->childbase.first; child; child = child->next)
07357         do_version_bone_roll_256(child);
07358 }
07359 
07360 static void do_versions_nodetree_dynamic_sockets(bNodeTree *ntree)
07361 {
07362     bNodeSocket *sock;
07363     for (sock=ntree->inputs.first; sock; sock=sock->next)
07364         sock->flag |= SOCK_DYNAMIC;
07365     for (sock=ntree->outputs.first; sock; sock=sock->next)
07366         sock->flag |= SOCK_DYNAMIC;
07367 }
07368 
07369 void convert_tface_mt(FileData *fd, Main *main)
07370 {
07371     Main *gmain;
07372 
07373     /* this is a delayed do_version (so it can create new materials) */
07374     if (main->versionfile < 259 || (main->versionfile == 259 && main->subversionfile < 3)) {
07375 
07376         //XXX hack, material.c uses G.main all over the place, instead of main
07377         // temporarily set G.main to the current main
07378         gmain = G.main;
07379         G.main = main;
07380 
07381         if(!(do_version_tface(main, 1))) {
07382             BKE_report(fd->reports, RPT_WARNING, "Texface conversion problem. Error in console");
07383         }
07384 
07385         //XXX hack, material.c uses G.main allover the place, instead of main
07386         G.main = gmain;
07387     }
07388 }
07389 
07390 static void do_versions_nodetree_image_default_alpha_output(bNodeTree *ntree)
07391 {
07392     bNode *node;
07393     bNodeSocket *sock;
07394     for (node=ntree->nodes.first; node; node=node->next) {
07395         if (ELEM(node->type, CMP_NODE_IMAGE, CMP_NODE_R_LAYERS)) {
07396             /* default Image output value should have 0 alpha */
07397             sock = node->outputs.first;
07398             ((bNodeSocketValueRGBA*)sock->default_value)->value[3] = 0.0f;
07399         }
07400     }
07401 }
07402 
07403 static void do_version_ntree_tex_mapping_260(void *UNUSED(data), ID *UNUSED(id), bNodeTree *ntree)
07404 {
07405     bNode *node;
07406 
07407     for(node=ntree->nodes.first; node; node=node->next) {
07408         if(node->type == SH_NODE_MAPPING) {
07409             TexMapping *tex_mapping;
07410 
07411             tex_mapping= node->storage;
07412             tex_mapping->projx= PROJ_X;
07413             tex_mapping->projy= PROJ_Y;
07414             tex_mapping->projz= PROJ_Z;
07415         }
07416     }
07417 }
07418 
07419 static void do_versions_nodetree_convert_angle(bNodeTree *ntree)
07420 {
07421     bNode *node;
07422     for (node=ntree->nodes.first; node; node=node->next) {
07423         if (node->type == CMP_NODE_ROTATE) {
07424             /* Convert degrees to radians. */
07425             bNodeSocket *sock = ((bNodeSocket*)node->inputs.first)->next;
07426             ((bNodeSocketValueFloat*)sock->default_value)->value = DEG2RADF(((bNodeSocketValueFloat*)sock->default_value)->value);
07427         }
07428         else if (node->type == CMP_NODE_DBLUR) {
07429             /* Convert degrees to radians. */
07430             NodeDBlurData *ndbd= node->storage;
07431             ndbd->angle = DEG2RADF(ndbd->angle);
07432             ndbd->spin = DEG2RADF(ndbd->spin);
07433         }
07434         else if (node->type == CMP_NODE_DEFOCUS) {
07435             /* Convert degrees to radians. */
07436             NodeDefocus *nqd = node->storage;
07437             /* XXX DNA char to float conversion seems to map the char value into the [0.0f, 1.0f] range... */
07438             nqd->rotation = DEG2RADF(nqd->rotation*255.0f);
07439         }
07440         else if (node->type == CMP_NODE_CHROMA_MATTE) {
07441             /* Convert degrees to radians. */
07442             NodeChroma *ndc = node->storage;
07443             ndc->t1 = DEG2RADF(ndc->t1);
07444             ndc->t2 = DEG2RADF(ndc->t2);
07445         }
07446         else if (node->type == CMP_NODE_GLARE) {
07447             /* Convert degrees to radians. */
07448             NodeGlare* ndg = node->storage;
07449             /* XXX DNA char to float conversion seems to map the char value into the [0.0f, 1.0f] range... */
07450             ndg->angle_ofs = DEG2RADF(ndg->angle_ofs*255.0f);
07451         }
07452         /* XXX TexMapping struct is used by other nodes too (at least node_composite_mapValue),
07453          *     but not the rot part...
07454          */
07455         else if (node->type == SH_NODE_MAPPING) {
07456             /* Convert degrees to radians. */
07457             TexMapping* tmap = node->storage;
07458             tmap->rot[0] = DEG2RADF(tmap->rot[0]);
07459             tmap->rot[1] = DEG2RADF(tmap->rot[1]);
07460             tmap->rot[2] = DEG2RADF(tmap->rot[2]);
07461         }
07462     }
07463 }
07464 
07465 void do_versions_image_settings_2_60(Scene *sce)
07466 {
07467     /* note: rd->subimtype is moved into indervidual settings now and no longer
07468      * exists */
07469     RenderData *rd= &sce->r;
07470     ImageFormatData *imf= &sce->r.im_format;
07471 
07472     imf->imtype= rd->imtype;
07473     imf->planes= rd->planes;
07474     imf->compress= rd->quality;
07475     imf->quality= rd->quality;
07476 
07477     /* default, was stored in multiple places, may override later */
07478     imf->depth= R_IMF_CHAN_DEPTH_8;
07479 
07480     /* openexr */
07481     imf->exr_codec = rd->quality & 7; /* strange but true! 0-4 are valid values, OPENEXR_COMPRESS */
07482 
07483     switch (imf->imtype) {
07484     case R_IMF_IMTYPE_OPENEXR:
07485         imf->depth=  (rd->subimtype & R_OPENEXR_HALF) ? R_IMF_CHAN_DEPTH_16 : R_IMF_CHAN_DEPTH_32;
07486         if (rd->subimtype & R_PREVIEW_JPG) {
07487             imf->flag |= R_IMF_FLAG_PREVIEW_JPG;
07488         }
07489         if (rd->subimtype & R_OPENEXR_ZBUF) {
07490             imf->flag |= R_IMF_FLAG_ZBUF;
07491         }
07492         break;
07493     case R_IMF_IMTYPE_TIFF:
07494         if (rd->subimtype & R_TIFF_16BIT) {
07495             imf->depth= R_IMF_CHAN_DEPTH_16;
07496         }
07497         break;
07498     case R_IMF_IMTYPE_JP2:
07499         if (rd->subimtype & R_JPEG2K_16BIT) {
07500             imf->depth= R_IMF_CHAN_DEPTH_16;
07501         }
07502         else if (rd->subimtype & R_JPEG2K_12BIT) {
07503             imf->depth= R_IMF_CHAN_DEPTH_12;
07504         }
07505 
07506         if (rd->subimtype & R_JPEG2K_YCC) {
07507             imf->jp2_flag |= R_IMF_JP2_FLAG_YCC;
07508         }
07509         if (rd->subimtype & R_JPEG2K_CINE_PRESET) {
07510             imf->jp2_flag |= R_IMF_JP2_FLAG_CINE_PRESET;
07511         }
07512         if (rd->subimtype & R_JPEG2K_CINE_48FPS) {
07513             imf->jp2_flag |= R_IMF_JP2_FLAG_CINE_48;
07514         }
07515         break;
07516     case R_IMF_IMTYPE_CINEON:
07517     case R_IMF_IMTYPE_DPX:
07518         if (rd->subimtype & R_CINEON_LOG) {
07519             imf->cineon_flag |= R_IMF_CINEON_FLAG_LOG;
07520         }
07521         break;
07522     }
07523 
07524 }
07525 
07526 /* socket use flags were only temporary before */
07527 static void do_versions_nodetree_socket_use_flags_2_62(bNodeTree *ntree)
07528 {
07529     bNode *node;
07530     bNodeSocket *sock;
07531     bNodeLink *link;
07532     
07533     for (node=ntree->nodes.first; node; node=node->next) {
07534         for (sock=node->inputs.first; sock; sock=sock->next)
07535             sock->flag &= ~SOCK_IN_USE;
07536         for (sock=node->outputs.first; sock; sock=sock->next)
07537             sock->flag &= ~SOCK_IN_USE;
07538     }
07539     for (sock=ntree->inputs.first; sock; sock=sock->next)
07540         sock->flag &= ~SOCK_IN_USE;
07541     for (sock=ntree->outputs.first; sock; sock=sock->next)
07542         sock->flag &= ~SOCK_IN_USE;
07543     
07544     for (link=ntree->links.first; link; link=link->next) {
07545         link->fromsock->flag |= SOCK_IN_USE;
07546         link->tosock->flag |= SOCK_IN_USE;
07547     }
07548 }
07549 
07550 /* set the SOCK_AUTO_HIDDEN flag on collapsed nodes */
07551 static void do_versions_nodetree_socket_auto_hidden_flags_2_62(bNodeTree *ntree)
07552 {
07553     bNode *node;
07554     bNodeSocket *sock;
07555     
07556     for (node=ntree->nodes.first; node; node=node->next) {
07557         if (node->flag & NODE_HIDDEN) {
07558             for (sock=node->inputs.first; sock; sock=sock->next) {
07559                 if (sock->link==NULL)
07560                     sock->flag |= SOCK_AUTO_HIDDEN;
07561             }
07562             for(sock=node->outputs.first; sock; sock= sock->next) {
07563                 if(nodeCountSocketLinks(ntree, sock)==0)
07564                     sock->flag |= SOCK_AUTO_HIDDEN;
07565             }
07566         }
07567         else {
07568             for(sock=node->inputs.first; sock; sock= sock->next)
07569                 sock->flag &= ~SOCK_AUTO_HIDDEN;
07570             for(sock=node->outputs.first; sock; sock= sock->next)
07571                 sock->flag &= ~SOCK_AUTO_HIDDEN;
07572         }
07573     }
07574 }
07575 
07576 static void do_versions(FileData *fd, Library *lib, Main *main)
07577 {
07578     /* WATCH IT!!!: pointers from libdata have not been converted */
07579 
07580     if(G.f & G_DEBUG)
07581         printf("read file %s\n  Version %d sub %d svn r%d\n", fd->relabase, main->versionfile, main->subversionfile, main->revision);
07582     
07583     if(main->versionfile == 100) {
07584         /* tex->extend and tex->imageflag have changed: */
07585         Tex *tex = main->tex.first;
07586         while(tex) {
07587             if(tex->id.flag & LIB_NEEDLINK) {
07588 
07589                 if(tex->extend==0) {
07590                     if(tex->xrepeat || tex->yrepeat) tex->extend= TEX_REPEAT;
07591                     else {
07592                         tex->extend= TEX_EXTEND;
07593                         tex->xrepeat= tex->yrepeat= 1;
07594                     }
07595                 }
07596 
07597             }
07598             tex= tex->id.next;
07599         }
07600     }
07601     if(main->versionfile <= 101) {
07602         /* frame mapping */
07603         Scene *sce = main->scene.first;
07604         while(sce) {
07605             sce->r.framapto= 100;
07606             sce->r.images= 100;
07607             sce->r.framelen= 1.0;
07608             sce= sce->id.next;
07609         }
07610     }
07611     if(main->versionfile <= 102) {
07612         /* init halo's at 1.0 */
07613         Material *ma = main->mat.first;
07614         while(ma) {
07615             ma->add= 1.0;
07616             ma= ma->id.next;
07617         }
07618     }
07619     if(main->versionfile <= 103) {
07620         /* new variable in object: colbits */
07621         Object *ob = main->object.first;
07622         int a;
07623         while(ob) {
07624             ob->colbits= 0;
07625             if(ob->totcol) {
07626                 for(a=0; a<ob->totcol; a++) {
07627                     if(ob->mat[a]) ob->colbits |= (1<<a);
07628                 }
07629             }
07630             ob= ob->id.next;
07631         }
07632     }
07633     if(main->versionfile <= 104) {
07634         /* timeoffs moved */
07635         Object *ob = main->object.first;
07636         while(ob) {
07637             if(ob->transflag & 1) {
07638                 ob->transflag -= 1;
07639                 //ob->ipoflag |= OB_OFFS_OB;
07640             }
07641             ob= ob->id.next;
07642         }
07643     }
07644     if(main->versionfile <= 105) {
07645         Object *ob = main->object.first;
07646         while(ob) {
07647             ob->dupon= 1; ob->dupoff= 0;
07648             ob->dupsta= 1; ob->dupend= 100;
07649             ob= ob->id.next;
07650         }
07651     }
07652     if(main->versionfile <= 106) {
07653         /* mcol changed */
07654         Mesh *me = main->mesh.first;
07655         while(me) {
07656             if(me->mcol) vcol_to_fcol(me);
07657             me= me->id.next;
07658         }
07659 
07660     }
07661     if(main->versionfile <= 107) {
07662         Object *ob;
07663         Scene *sce = main->scene.first;
07664         while(sce) {
07665             sce->r.mode |= R_GAMMA;
07666             sce= sce->id.next;
07667         }
07668         ob= main->object.first;
07669         while(ob) {
07670             //ob->ipoflag |= OB_OFFS_PARENT;
07671             if(ob->dt==0) ob->dt= OB_SOLID;
07672             ob= ob->id.next;
07673         }
07674 
07675     }
07676     if(main->versionfile <= 109) {
07677         /* new variable: gridlines */
07678         bScreen *sc = main->screen.first;
07679         while(sc) {
07680             ScrArea *sa= sc->areabase.first;
07681             while(sa) {
07682                 SpaceLink *sl= sa->spacedata.first;
07683                 while (sl) {
07684                     if (sl->spacetype==SPACE_VIEW3D) {
07685                         View3D *v3d= (View3D*) sl;
07686 
07687                         if (v3d->gridlines==0) v3d->gridlines= 20;
07688                     }
07689                     sl= sl->next;
07690                 }
07691                 sa= sa->next;
07692             }
07693             sc= sc->id.next;
07694         }
07695     }
07696     if(main->versionfile <= 113) {
07697         Material *ma = main->mat.first;
07698         while(ma) {
07699             if(ma->flaresize==0.0f) ma->flaresize= 1.0f;
07700             ma->subsize= 1.0f;
07701             ma->flareboost= 1.0f;
07702             ma= ma->id.next;
07703         }
07704     }
07705 
07706     if(main->versionfile <= 134) {
07707         Tex *tex = main->tex.first;
07708         while (tex) {
07709             if ((tex->rfac == 0.0f) &&
07710                 (tex->gfac == 0.0f) &&
07711                 (tex->bfac == 0.0f)) {
07712                 tex->rfac = 1.0f;
07713                 tex->gfac = 1.0f;
07714                 tex->bfac = 1.0f;
07715                 tex->filtersize = 1.0f;
07716             }
07717             tex = tex->id.next;
07718         }
07719     }
07720     if(main->versionfile <= 140) {
07721         /* r-g-b-fac in texture */
07722         Tex *tex = main->tex.first;
07723         while (tex) {
07724             if ((tex->rfac == 0.0f) &&
07725                 (tex->gfac == 0.0f) &&
07726                 (tex->bfac == 0.0f)) {
07727                 tex->rfac = 1.0f;
07728                 tex->gfac = 1.0f;
07729                 tex->bfac = 1.0f;
07730                 tex->filtersize = 1.0f;
07731             }
07732             tex = tex->id.next;
07733         }
07734     }
07735     if(main->versionfile <= 153) {
07736         Scene *sce = main->scene.first;
07737         while(sce) {
07738             if(sce->r.blurfac==0.0f) sce->r.blurfac= 1.0f;
07739             sce= sce->id.next;
07740         }
07741     }
07742     if(main->versionfile <= 163) {
07743         Scene *sce = main->scene.first;
07744         while(sce) {
07745             if(sce->r.frs_sec==0) sce->r.frs_sec= 25;
07746             sce= sce->id.next;
07747         }
07748     }
07749     if(main->versionfile <= 164) {
07750         Mesh *me= main->mesh.first;
07751         while(me) {
07752             me->smoothresh= 30;
07753             me= me->id.next;
07754         }
07755     }
07756     if(main->versionfile <= 165) {
07757         Mesh *me= main->mesh.first;
07758         TFace *tface;
07759         int nr;
07760         char *cp;
07761 
07762         while(me) {
07763             if(me->tface) {
07764                 nr= me->totface;
07765                 tface= me->tface;
07766                 while(nr--) {
07767                     cp= (char *)&tface->col[0];
07768                     if(cp[1]>126) cp[1]= 255; else cp[1]*=2;
07769                     if(cp[2]>126) cp[2]= 255; else cp[2]*=2;
07770                     if(cp[3]>126) cp[3]= 255; else cp[3]*=2;
07771                     cp= (char *)&tface->col[1];
07772                     if(cp[1]>126) cp[1]= 255; else cp[1]*=2;
07773                     if(cp[2]>126) cp[2]= 255; else cp[2]*=2;
07774                     if(cp[3]>126) cp[3]= 255; else cp[3]*=2;
07775                     cp= (char *)&tface->col[2];
07776                     if(cp[1]>126) cp[1]= 255; else cp[1]*=2;
07777                     if(cp[2]>126) cp[2]= 255; else cp[2]*=2;
07778                     if(cp[3]>126) cp[3]= 255; else cp[3]*=2;
07779                     cp= (char *)&tface->col[3];
07780                     if(cp[1]>126) cp[1]= 255; else cp[1]*=2;
07781                     if(cp[2]>126) cp[2]= 255; else cp[2]*=2;
07782                     if(cp[3]>126) cp[3]= 255; else cp[3]*=2;
07783 
07784                     tface++;
07785                 }
07786             }
07787             me= me->id.next;
07788         }
07789     }
07790 
07791     if(main->versionfile <= 169) {
07792         Mesh *me= main->mesh.first;
07793         while(me) {
07794             if(me->subdiv==0) me->subdiv= 1;
07795             me= me->id.next;
07796         }
07797     }
07798 
07799     if(main->versionfile <= 169) {
07800         bScreen *sc= main->screen.first;
07801         while(sc) {
07802             ScrArea *sa= sc->areabase.first;
07803             while(sa) {
07804                 SpaceLink *sl= sa->spacedata.first;
07805                 while(sl) {
07806                     if(sl->spacetype==SPACE_IPO) {
07807                         SpaceIpo *sipo= (SpaceIpo*) sl;
07808                         sipo->v2d.max[0]= 15000.0;
07809                     }
07810                     sl= sl->next;
07811                 }
07812                 sa= sa->next;
07813             }
07814             sc= sc->id.next;
07815         }
07816     }
07817 
07818     if(main->versionfile <= 170) {
07819         Object *ob = main->object.first;
07820         PartEff *paf;
07821         while (ob) {
07822             paf = do_version_give_parteff_245(ob);
07823             if (paf) {
07824                 if (paf->staticstep == 0) {
07825                     paf->staticstep= 5;
07826                 }
07827             }
07828             ob = ob->id.next;
07829         }
07830     }
07831 
07832     if(main->versionfile <= 171) {
07833         bScreen *sc= main->screen.first;
07834         while(sc) {
07835             ScrArea *sa= sc->areabase.first;
07836             while(sa) {
07837                 SpaceLink *sl= sa->spacedata.first;
07838                 while(sl) {
07839                     if(sl->spacetype==SPACE_TEXT) {
07840                         SpaceText *st= (SpaceText*) sl;
07841                         st->lheight= 12;
07842                     }
07843                     sl= sl->next;
07844                 }
07845                 sa= sa->next;
07846             }
07847             sc= sc->id.next;
07848         }
07849     }
07850 
07851     if(main->versionfile <= 173) {
07852         int a, b;
07853         Mesh *me= main->mesh.first;
07854         while(me) {
07855             if(me->tface) {
07856                 TFace *tface= me->tface;
07857                 for(a=0; a<me->totface; a++, tface++) {
07858                     for(b=0; b<4; b++) {
07859                         tface->uv[b][0]/= 32767.0f;
07860                         tface->uv[b][1]/= 32767.0f;
07861                     }
07862                 }
07863             }
07864             me= me->id.next;
07865         }
07866     }
07867 
07868     if(main->versionfile <= 191) {
07869         Object *ob= main->object.first;
07870         Material *ma = main->mat.first;
07871 
07872         /* let faces have default add factor of 0.0 */
07873         while(ma) {
07874           if (!(ma->mode & MA_HALO)) ma->add = 0.0;
07875           ma = ma->id.next;
07876         }
07877 
07878         while(ob) {
07879             ob->mass= 1.0f;
07880             ob->damping= 0.1f;
07881             /*ob->quat[1]= 1.0f;*/ /* quats arnt used yet */
07882             ob= ob->id.next;
07883         }
07884     }
07885 
07886     if(main->versionfile <= 193) {
07887         Object *ob= main->object.first;
07888         while(ob) {
07889             ob->inertia= 1.0f;
07890             ob->rdamping= 0.1f;
07891             ob= ob->id.next;
07892         }
07893     }
07894 
07895     if(main->versionfile <= 196) {
07896         Mesh *me= main->mesh.first;
07897         int a, b;
07898         while(me) {
07899             if(me->tface) {
07900                 TFace *tface= me->tface;
07901                 for(a=0; a<me->totface; a++, tface++) {
07902                     for(b=0; b<4; b++) {
07903                         tface->mode |= TF_DYNAMIC;
07904                         tface->mode &= ~TF_INVISIBLE;
07905                     }
07906                 }
07907             }
07908             me= me->id.next;
07909         }
07910     }
07911 
07912     if(main->versionfile <= 200) {
07913         Object *ob= main->object.first;
07914         while(ob) {
07915             ob->scaflag = ob->gameflag & (OB_DO_FH|OB_ROT_FH|OB_ANISOTROPIC_FRICTION|OB_GHOST|OB_RIGID_BODY|OB_BOUNDS);
07916                 /* 64 is do_fh */
07917             ob->gameflag &= ~(OB_ROT_FH|OB_ANISOTROPIC_FRICTION|OB_GHOST|OB_RIGID_BODY|OB_BOUNDS);
07918             ob = ob->id.next;
07919         }
07920     }
07921 
07922     if(main->versionfile <= 201) {
07923         /* add-object + end-object are joined to edit-object actuator */
07924         Object *ob = main->object.first;
07925         bProperty *prop;
07926         bActuator *act;
07927         bIpoActuator *ia;
07928         bEditObjectActuator *eoa;
07929         bAddObjectActuator *aoa;
07930         while (ob) {
07931             act = ob->actuators.first;
07932             while (act) {
07933                 if(act->type==ACT_IPO) {
07934                     ia= act->data;
07935                     prop= get_ob_property(ob, ia->name);
07936                     if(prop) {
07937                         ia->type= ACT_IPO_FROM_PROP;
07938                     }
07939                 }
07940                 else if(act->type==ACT_ADD_OBJECT) {
07941                     aoa= act->data;
07942                     eoa= MEM_callocN(sizeof(bEditObjectActuator), "edit ob act");
07943                     eoa->type= ACT_EDOB_ADD_OBJECT;
07944                     eoa->ob= aoa->ob;
07945                     eoa->time= aoa->time;
07946                     MEM_freeN(aoa);
07947                     act->data= eoa;
07948                     act->type= act->otype= ACT_EDIT_OBJECT;
07949                 }
07950                 else if(act->type==ACT_END_OBJECT) {
07951                     eoa= MEM_callocN(sizeof(bEditObjectActuator), "edit ob act");
07952                     eoa->type= ACT_EDOB_END_OBJECT;
07953                     act->data= eoa;
07954                     act->type= act->otype= ACT_EDIT_OBJECT;
07955                 }
07956                 act= act->next;
07957             }
07958             ob = ob->id.next;
07959         }
07960     }
07961 
07962     if(main->versionfile <= 202) {
07963         /* add-object and end-object are joined to edit-object
07964          * actuator */
07965         Object *ob= main->object.first;
07966         bActuator *act;
07967         bObjectActuator *oa;
07968         while(ob) {
07969             act= ob->actuators.first;
07970             while(act) {
07971                 if(act->type==ACT_OBJECT) {
07972                     oa= act->data;
07973                     oa->flag &= ~(ACT_TORQUE_LOCAL|ACT_DROT_LOCAL);     /* this actuator didn't do local/glob rot before */
07974                 }
07975                 act= act->next;
07976             }
07977             ob= ob->id.next;
07978         }
07979     }
07980 
07981     if(main->versionfile <= 204) {
07982         /* patches for new physics */
07983         Object *ob= main->object.first;
07984         bActuator *act;
07985         bObjectActuator *oa;
07986         bSound *sound;
07987         while(ob) {
07988 
07989             /* please check this for demo20 files like
07990              * original Egypt levels etc.  converted
07991              * rotation factor of 50 is not workable */
07992             act= ob->actuators.first;
07993             while(act) {
07994                 if(act->type==ACT_OBJECT) {
07995                     oa= act->data;
07996 
07997                     oa->forceloc[0]*= 25.0f;
07998                     oa->forceloc[1]*= 25.0f;
07999                     oa->forceloc[2]*= 25.0f;
08000 
08001                     oa->forcerot[0]*= 10.0f;
08002                     oa->forcerot[1]*= 10.0f;
08003                     oa->forcerot[2]*= 10.0f;
08004                 }
08005                 act= act->next;
08006             }
08007             ob= ob->id.next;
08008         }
08009 
08010         sound = main->sound.first;
08011         while (sound) {
08012             if (sound->volume < 0.01f) {
08013                 sound->volume = 1.0f;
08014             }
08015             sound = sound->id.next;
08016         }
08017     }
08018 
08019     if(main->versionfile <= 205) {
08020         /* patches for new physics */
08021         Object *ob= main->object.first;
08022         bActuator *act;
08023         bSensor *sens;
08024         bEditObjectActuator *oa;
08025         bRaySensor *rs;
08026         bCollisionSensor *cs;
08027         while(ob) {
08028             /* Set anisotropic friction off for old objects,
08029              * values to 1.0.  */
08030             ob->gameflag &= ~OB_ANISOTROPIC_FRICTION;
08031             ob->anisotropicFriction[0] = 1.0;
08032             ob->anisotropicFriction[1] = 1.0;
08033             ob->anisotropicFriction[2] = 1.0;
08034 
08035             act= ob->actuators.first;
08036             while(act) {
08037                 if(act->type==ACT_EDIT_OBJECT) {
08038                     /* Zero initial velocity for newly
08039                      * added objects */
08040                     oa= act->data;
08041                     oa->linVelocity[0] = 0.0;
08042                     oa->linVelocity[1] = 0.0;
08043                     oa->linVelocity[2] = 0.0;
08044                     oa->localflag = 0;
08045                 }
08046                 act= act->next;
08047             }
08048 
08049             sens= ob->sensors.first;
08050             while (sens) {
08051                 /* Extra fields for radar sensors. */
08052                 if(sens->type == SENS_RADAR) {
08053                     bRadarSensor *s = sens->data;
08054                     s->range = 10000.0;
08055                 }
08056 
08057                 /* Pulsing: defaults for new sensors. */
08058                 if(sens->type != SENS_ALWAYS) {
08059                     sens->pulse = 0;
08060                     sens->freq = 0;
08061                 } else {
08062                     sens->pulse = 1;
08063                 }
08064 
08065                 /* Invert: off. */
08066                 sens->invert = 0;
08067 
08068                 /* Collision and ray: default = trigger
08069                  * on property. The material field can
08070                  * remain empty. */
08071                 if(sens->type == SENS_COLLISION) {
08072                     cs = (bCollisionSensor*) sens->data;
08073                     cs->mode = 0;
08074                 }
08075                 if(sens->type == SENS_RAY) {
08076                     rs = (bRaySensor*) sens->data;
08077                     rs->mode = 0;
08078                 }
08079                 sens = sens->next;
08080             }
08081             ob= ob->id.next;
08082         }
08083         /* have to check the exact multiplier */
08084     }
08085 
08086     if(main->versionfile <= 211) {
08087         /* Render setting: per scene, the applicable gamma value
08088          * can be set. Default is 1.0, which means no
08089          * correction.  */
08090         bActuator *act;
08091         bObjectActuator *oa;
08092         Object *ob;
08093 
08094         /* added alpha in obcolor */
08095         ob= main->object.first;
08096         while(ob) {
08097             ob->col[3]= 1.0;
08098             ob= ob->id.next;
08099         }
08100 
08101         /* added alpha in obcolor */
08102         ob= main->object.first;
08103         while(ob) {
08104             act= ob->actuators.first;
08105             while(act) {
08106                 if (act->type==ACT_OBJECT) {
08107                     /* multiply velocity with 50 in old files */
08108                     oa= act->data;
08109                     if (fabsf(oa->linearvelocity[0]) >= 0.01f)
08110                         oa->linearvelocity[0] *= 50.0f;
08111                     if (fabsf(oa->linearvelocity[1]) >= 0.01f)
08112                         oa->linearvelocity[1] *= 50.0f;
08113                     if (fabsf(oa->linearvelocity[2]) >= 0.01f)
08114                         oa->linearvelocity[2] *= 50.0f;
08115                     if (fabsf(oa->angularvelocity[0])>=0.01f)
08116                         oa->angularvelocity[0] *= 50.0f;
08117                     if (fabsf(oa->angularvelocity[1])>=0.01f)
08118                         oa->angularvelocity[1] *= 50.0f;
08119                     if (fabsf(oa->angularvelocity[2])>=0.01f)
08120                         oa->angularvelocity[2] *= 50.0f;
08121                 }
08122                 act= act->next;
08123             }
08124             ob= ob->id.next;
08125         }
08126     }
08127 
08128     if(main->versionfile <= 212) {
08129 
08130         bSound* sound;
08131         bProperty *prop;
08132         Object *ob;
08133         Mesh *me;
08134 
08135         sound = main->sound.first;
08136         while (sound)
08137         {
08138             sound->max_gain = 1.0;
08139             sound->min_gain = 0.0;
08140             sound->distance = 1.0;
08141 
08142             if (sound->attenuation > 0.0f)
08143                 sound->flags |= SOUND_FLAGS_3D;
08144             else
08145                 sound->flags &= ~SOUND_FLAGS_3D;
08146 
08147             sound = sound->id.next;
08148         }
08149 
08150         ob = main->object.first;
08151 
08152         while (ob) {
08153             prop= ob->prop.first;
08154             while(prop) {
08155                 if (prop->type == GPROP_TIME) {
08156                     // convert old GPROP_TIME values from int to float
08157                     *((float *)&prop->data) = (float) prop->data;
08158                 }
08159 
08160                 prop= prop->next;
08161             }
08162             ob = ob->id.next;
08163         }
08164 
08165             /* me->subdiv changed to reflect the actual reparametization
08166              * better, and smeshes were removed - if it was a smesh make
08167              * it a subsurf, and reset the subdiv level because subsurf
08168              * takes a lot more work to calculate.
08169              */
08170         for (me= main->mesh.first; me; me= me->id.next) {
08171             if (me->flag&ME_SMESH) {
08172                 me->flag&= ~ME_SMESH;
08173                 me->flag|= ME_SUBSURF;
08174 
08175                 me->subdiv= 1;
08176             } else {
08177                 if (me->subdiv<2)
08178                     me->subdiv= 1;
08179                 else
08180                     me->subdiv--;
08181             }
08182         }
08183     }
08184 
08185     if(main->versionfile <= 220) {
08186         Object *ob;
08187         Mesh *me;
08188 
08189         ob = main->object.first;
08190 
08191         /* adapt form factor in order to get the 'old' physics
08192          * behaviour back...*/
08193 
08194         while (ob) {
08195             /* in future, distinguish between different
08196              * object bounding shapes */
08197             ob->formfactor = 0.4f;
08198             /* patch form factor , note that inertia equiv radius
08199              * of a rotation symmetrical obj */
08200             if (ob->inertia != 1.0f) {
08201                 ob->formfactor /= ob->inertia * ob->inertia;
08202             }
08203             ob = ob->id.next;
08204         }
08205 
08206             /* Began using alpha component of vertex colors, but
08207              * old file vertex colors are undefined, reset them
08208              * to be fully opaque. -zr
08209              */
08210         for (me= main->mesh.first; me; me= me->id.next) {
08211             if (me->mcol) {
08212                 int i;
08213 
08214                 for (i=0; i<me->totface*4; i++) {
08215                     MCol *mcol= &me->mcol[i];
08216                     mcol->a= 255;
08217                 }
08218             }
08219             if (me->tface) {
08220                 int i, j;
08221 
08222                 for (i=0; i<me->totface; i++) {
08223                     TFace *tf= &((TFace*) me->tface)[i];
08224 
08225                     for (j=0; j<4; j++) {
08226                         char *col= (char*) &tf->col[j];
08227 
08228                         col[0]= 255;
08229                     }
08230                 }
08231             }
08232         }
08233     }
08234     if(main->versionfile <= 221) {
08235         Scene *sce= main->scene.first;
08236 
08237         // new variables for std-alone player and runtime
08238         while(sce) {
08239 
08240             sce->r.xplay= 640;
08241             sce->r.yplay= 480;
08242             sce->r.freqplay= 60;
08243 
08244             sce= sce->id.next;
08245         }
08246 
08247     }
08248     if(main->versionfile <= 222) {
08249         Scene *sce= main->scene.first;
08250 
08251         // new variables for std-alone player and runtime
08252         while(sce) {
08253 
08254             sce->r.depth= 32;
08255 
08256             sce= sce->id.next;
08257         }
08258     }
08259 
08260 
08261     if(main->versionfile <= 223) {
08262         VFont *vf;
08263         Image *ima;
08264         Object *ob;
08265 
08266         for (vf= main->vfont.first; vf; vf= vf->id.next) {
08267             if (strcmp(vf->name+strlen(vf->name)-6, ".Bfont")==0) {
08268                 strcpy(vf->name, FO_BUILTIN_NAME);
08269             }
08270         }
08271 
08272         /* Old textures animate at 25 FPS */
08273         for (ima = main->image.first; ima; ima=ima->id.next){
08274             ima->animspeed = 25;
08275         }
08276 
08277             /* Zr remapped some keyboard codes to be linear (stupid zr) */
08278         for (ob= main->object.first; ob; ob= ob->id.next) {
08279             bSensor *sens;
08280 
08281             for (sens= ob->sensors.first; sens; sens= sens->next) {
08282                 if (sens->type==SENS_KEYBOARD) {
08283                     bKeyboardSensor *ks= sens->data;
08284 
08285                     ks->key= map_223_keybd_code_to_224_keybd_code(ks->key);
08286                     ks->qual= map_223_keybd_code_to_224_keybd_code(ks->qual);
08287                     ks->qual2= map_223_keybd_code_to_224_keybd_code(ks->qual2);
08288                 }
08289             }
08290         }
08291     }
08292     if(main->versionfile <= 224) {
08293         bSound* sound;
08294         Scene *sce;
08295         Mesh *me;
08296         bScreen *sc;
08297 
08298         for (sound=main->sound.first; sound; sound=sound->id.next) {
08299             if (sound->packedfile) {
08300                 if (sound->newpackedfile == NULL) {
08301                     sound->newpackedfile = sound->packedfile;
08302                 }
08303                 sound->packedfile = NULL;
08304             }
08305         }
08306         /* Make sure that old subsurf meshes don't have zero subdivision level for rendering */
08307         for (me=main->mesh.first; me; me=me->id.next){
08308             if ((me->flag & ME_SUBSURF) && (me->subdivr==0))
08309                 me->subdivr=me->subdiv;
08310         }
08311 
08312         for (sce= main->scene.first; sce; sce= sce->id.next) {
08313             sce->r.stereomode = 1;  // no stereo
08314         }
08315 
08316             /* some oldfile patch, moved from set_func_space */
08317         for (sc= main->screen.first; sc; sc= sc->id.next) {
08318             ScrArea *sa;
08319 
08320             for (sa= sc->areabase.first; sa; sa= sa->next) {
08321                 SpaceLink *sl;
08322 
08323                 for (sl= sa->spacedata.first; sl; sl= sl->next) {
08324                     if (sl->spacetype==SPACE_IPO) {
08325                         SpaceSeq *sseq= (SpaceSeq*) sl;
08326                         sseq->v2d.keeptot= 0;
08327                     }
08328                 }
08329             }
08330         }
08331 
08332     }
08333 
08334 
08335     if(main->versionfile <= 225) {
08336         World *wo;
08337         /* Use Sumo for old games */
08338         for (wo = main->world.first; wo; wo= wo->id.next) {
08339             wo->physicsEngine = 2;
08340         }
08341     }
08342 
08343     if(main->versionfile <= 227) {
08344         Scene *sce;
08345         Material *ma;
08346         bScreen *sc;
08347         Object *ob;
08348 
08349         /*  As of now, this insures that the transition from the old Track system
08350             to the new full constraint Track is painless for everyone. - theeth
08351         */
08352         ob = main->object.first;
08353 
08354         while (ob) {
08355             ListBase *list;
08356             list = &ob->constraints;
08357 
08358             /* check for already existing TrackTo constraint
08359                set their track and up flag correctly */
08360 
08361             if (list){
08362                 bConstraint *curcon;
08363                 for (curcon = list->first; curcon; curcon=curcon->next){
08364                     if (curcon->type == CONSTRAINT_TYPE_TRACKTO){
08365                         bTrackToConstraint *data = curcon->data;
08366                         data->reserved1 = ob->trackflag;
08367                         data->reserved2 = ob->upflag;
08368                     }
08369                 }
08370             }
08371 
08372             if (ob->type == OB_ARMATURE) {
08373                 if (ob->pose){
08374                     bConstraint *curcon;
08375                     bPoseChannel *pchan;
08376                     for (pchan = ob->pose->chanbase.first;
08377                          pchan; pchan=pchan->next){
08378                         for (curcon = pchan->constraints.first;
08379                              curcon; curcon=curcon->next){
08380                             if (curcon->type == CONSTRAINT_TYPE_TRACKTO){
08381                                 bTrackToConstraint *data = curcon->data;
08382                                 data->reserved1 = ob->trackflag;
08383                                 data->reserved2 = ob->upflag;
08384                             }
08385                         }
08386                     }
08387                 }
08388             }
08389 
08390             /* Change Ob->Track in real TrackTo constraint */
08391             do_version_old_trackto_to_constraints(ob);
08392             
08393             ob = ob->id.next;
08394         }
08395 
08396 
08397         for (sce= main->scene.first; sce; sce= sce->id.next) {
08398             sce->audio.mixrate = 44100;
08399             sce->audio.flag |= AUDIO_SCRUB;
08400             sce->r.mode |= R_ENVMAP;
08401         }
08402         // init new shader vars
08403         for (ma= main->mat.first; ma; ma= ma->id.next) {
08404             ma->refrac= 4.0f;
08405             ma->roughness= 0.5f;
08406             ma->param[0]= 0.5f;
08407             ma->param[1]= 0.1f;
08408             ma->param[2]= 0.1f;
08409             ma->param[3]= 0.05f;
08410         }
08411         // patch for old wrong max view2d settings, allows zooming out more
08412         for (sc= main->screen.first; sc; sc= sc->id.next) {
08413             ScrArea *sa;
08414 
08415             for (sa= sc->areabase.first; sa; sa= sa->next) {
08416                 SpaceLink *sl;
08417 
08418                 for (sl= sa->spacedata.first; sl; sl= sl->next) {
08419                     if (sl->spacetype==SPACE_ACTION) {
08420                         SpaceAction *sac= (SpaceAction *) sl;
08421                         sac->v2d.max[0]= 32000;
08422                     }
08423                     else if (sl->spacetype==SPACE_NLA) {
08424                         SpaceNla *sla= (SpaceNla *) sl;
08425                         sla->v2d.max[0]= 32000;
08426                     }
08427                 }
08428             }
08429         }
08430     }
08431     if(main->versionfile <= 228) {
08432         Scene *sce;
08433         bScreen *sc;
08434         Object *ob;
08435 
08436 
08437         /*  As of now, this insures that the transition from the old Track system
08438             to the new full constraint Track is painless for everyone.*/
08439         ob = main->object.first;
08440 
08441         while (ob) {
08442             ListBase *list;
08443             list = &ob->constraints;
08444 
08445             /* check for already existing TrackTo constraint
08446                set their track and up flag correctly */
08447 
08448             if (list){
08449                 bConstraint *curcon;
08450                 for (curcon = list->first; curcon; curcon=curcon->next){
08451                     if (curcon->type == CONSTRAINT_TYPE_TRACKTO){
08452                         bTrackToConstraint *data = curcon->data;
08453                         data->reserved1 = ob->trackflag;
08454                         data->reserved2 = ob->upflag;
08455                     }
08456                 }
08457             }
08458 
08459             if (ob->type == OB_ARMATURE) {
08460                 if (ob->pose){
08461                     bConstraint *curcon;
08462                     bPoseChannel *pchan;
08463                     for (pchan = ob->pose->chanbase.first;
08464                          pchan; pchan=pchan->next){
08465                         for (curcon = pchan->constraints.first;
08466                              curcon; curcon=curcon->next){
08467                             if (curcon->type == CONSTRAINT_TYPE_TRACKTO){
08468                                 bTrackToConstraint *data = curcon->data;
08469                                 data->reserved1 = ob->trackflag;
08470                                 data->reserved2 = ob->upflag;
08471                             }
08472                         }
08473                     }
08474                 }
08475             }
08476 
08477             ob = ob->id.next;
08478         }
08479 
08480         for (sce= main->scene.first; sce; sce= sce->id.next) {
08481             sce->r.mode |= R_ENVMAP;
08482         }
08483 
08484         // convert old mainb values for new button panels
08485         for (sc= main->screen.first; sc; sc= sc->id.next) {
08486             ScrArea *sa;
08487 
08488             for (sa= sc->areabase.first; sa; sa= sa->next) {
08489                 SpaceLink *sl;
08490 
08491                 for (sl= sa->spacedata.first; sl; sl= sl->next) {
08492                     if (sl->spacetype==SPACE_BUTS) {
08493                         SpaceButs *sbuts= (SpaceButs *) sl;
08494 
08495                         sbuts->v2d.maxzoom= 1.2f;
08496                         sbuts->align= 1;    /* horizontal default */
08497                     
08498                         if(sbuts->mainb==BUTS_LAMP) {
08499                             sbuts->mainb= CONTEXT_SHADING;
08500                             //sbuts->tab[CONTEXT_SHADING]= TAB_SHADING_LAMP;
08501                         }
08502                         else if(sbuts->mainb==BUTS_MAT) {
08503                             sbuts->mainb= CONTEXT_SHADING;
08504                             //sbuts->tab[CONTEXT_SHADING]= TAB_SHADING_MAT;
08505                         }
08506                         else if(sbuts->mainb==BUTS_TEX) {
08507                             sbuts->mainb= CONTEXT_SHADING;
08508                             //sbuts->tab[CONTEXT_SHADING]= TAB_SHADING_TEX;
08509                         }
08510                         else if(sbuts->mainb==BUTS_ANIM) {
08511                             sbuts->mainb= CONTEXT_OBJECT;
08512                         }
08513                         else if(sbuts->mainb==BUTS_WORLD) {
08514                             sbuts->mainb= CONTEXT_SCENE;
08515                             //sbuts->tab[CONTEXT_SCENE]= TAB_SCENE_WORLD;
08516                         }
08517                         else if(sbuts->mainb==BUTS_RENDER) {
08518                             sbuts->mainb= CONTEXT_SCENE;
08519                             //sbuts->tab[CONTEXT_SCENE]= TAB_SCENE_RENDER;
08520                         }
08521                         else if(sbuts->mainb==BUTS_GAME) {
08522                             sbuts->mainb= CONTEXT_LOGIC;
08523                         }
08524                         else if(sbuts->mainb==BUTS_FPAINT) {
08525                             sbuts->mainb= CONTEXT_EDITING;
08526                         }
08527                         else if(sbuts->mainb==BUTS_RADIO) {
08528                             sbuts->mainb= CONTEXT_SHADING;
08529                             //sbuts->tab[CONTEXT_SHADING]= TAB_SHADING_RAD;
08530                         }
08531                         else if(sbuts->mainb==BUTS_CONSTRAINT) {
08532                             sbuts->mainb= CONTEXT_OBJECT;
08533                         }
08534                         else if(sbuts->mainb==BUTS_SCRIPT) {
08535                             sbuts->mainb= CONTEXT_OBJECT;
08536                         }
08537                         else if(sbuts->mainb==BUTS_EDIT) {
08538                             sbuts->mainb= CONTEXT_EDITING;
08539                         }
08540                         else sbuts->mainb= CONTEXT_SCENE;
08541                     }
08542                 }
08543             }
08544         }
08545     }
08546     /* ton: made this 230 instead of 229,
08547        to be sure (tuho files) and this is a reliable check anyway
08548        nevertheless, we might need to think over a fitness (initialize)
08549        check apart from the do_versions() */
08550 
08551     if(main->versionfile <= 230) {
08552         bScreen *sc;
08553 
08554         // new variable blockscale, for panels in any area
08555         for (sc= main->screen.first; sc; sc= sc->id.next) {
08556             ScrArea *sa;
08557 
08558             for (sa= sc->areabase.first; sa; sa= sa->next) {
08559                 SpaceLink *sl;
08560 
08561                 for (sl= sa->spacedata.first; sl; sl= sl->next) {
08562                     if(sl->blockscale==0.0f) sl->blockscale= 0.7f;
08563                     /* added: 5x better zoom in for action */
08564                     if(sl->spacetype==SPACE_ACTION) {
08565                         SpaceAction *sac= (SpaceAction *)sl;
08566                         sac->v2d.maxzoom= 50;
08567                     }
08568                 }
08569             }
08570         }
08571     }
08572     if(main->versionfile <= 231) {
08573         /* new bit flags for showing/hiding grid floor and axes */
08574         bScreen *sc = main->screen.first;
08575         while(sc) {
08576             ScrArea *sa= sc->areabase.first;
08577             while(sa) {
08578                 SpaceLink *sl= sa->spacedata.first;
08579                 while (sl) {
08580                     if (sl->spacetype==SPACE_VIEW3D) {
08581                         View3D *v3d= (View3D*) sl;
08582 
08583                         if (v3d->gridflag==0) {
08584                             v3d->gridflag |= V3D_SHOW_X;
08585                             v3d->gridflag |= V3D_SHOW_Y;
08586                             v3d->gridflag |= V3D_SHOW_FLOOR;
08587                             v3d->gridflag &= ~V3D_SHOW_Z;
08588                         }
08589                     }
08590                     sl= sl->next;
08591                 }
08592                 sa= sa->next;
08593             }
08594             sc= sc->id.next;
08595         }
08596     }
08597     if(main->versionfile <= 231) {
08598         Material *ma= main->mat.first;
08599         bScreen *sc = main->screen.first;
08600         Scene *sce;
08601         Lamp *la;
08602         World *wrld;
08603 
08604         /* introduction of raytrace */
08605         while(ma) {
08606             if(ma->fresnel_tra_i==0.0f) ma->fresnel_tra_i= 1.25f;
08607             if(ma->fresnel_mir_i==0.0f) ma->fresnel_mir_i= 1.25f;
08608 
08609             ma->ang= 1.0;
08610             ma->ray_depth= 2;
08611             ma->ray_depth_tra= 2;
08612             ma->fresnel_tra= 0.0;
08613             ma->fresnel_mir= 0.0;
08614 
08615             ma= ma->id.next;
08616         }
08617         sce= main->scene.first;
08618         while(sce) {
08619             if(sce->r.gauss==0.0f) sce->r.gauss= 1.0f;
08620             sce= sce->id.next;
08621         }
08622         la= main->lamp.first;
08623         while(la) {
08624             if(la->k==0.0f) la->k= 1.0;
08625             if(la->ray_samp==0) la->ray_samp= 1;
08626             if(la->ray_sampy==0) la->ray_sampy= 1;
08627             if(la->ray_sampz==0) la->ray_sampz= 1;
08628             if(la->area_size==0.0f) la->area_size= 1.0f;
08629             if(la->area_sizey==0.0f) la->area_sizey= 1.0f;
08630             if(la->area_sizez==0.0f) la->area_sizez= 1.0f;
08631             la= la->id.next;
08632         }
08633         wrld= main->world.first;
08634         while(wrld) {
08635             if(wrld->range==0.0f) {
08636                 wrld->range= 1.0f/wrld->exposure;
08637             }
08638             wrld= wrld->id.next;
08639         }
08640 
08641         /* new bit flags for showing/hiding grid floor and axes */
08642 
08643         while(sc) {
08644             ScrArea *sa= sc->areabase.first;
08645             while(sa) {
08646                 SpaceLink *sl= sa->spacedata.first;
08647                 while (sl) {
08648                     if (sl->spacetype==SPACE_VIEW3D) {
08649                         View3D *v3d= (View3D*) sl;
08650 
08651                         if (v3d->gridflag==0) {
08652                             v3d->gridflag |= V3D_SHOW_X;
08653                             v3d->gridflag |= V3D_SHOW_Y;
08654                             v3d->gridflag |= V3D_SHOW_FLOOR;
08655                             v3d->gridflag &= ~V3D_SHOW_Z;
08656                         }
08657                     }
08658                     sl= sl->next;
08659                 }
08660                 sa= sa->next;
08661             }
08662             sc= sc->id.next;
08663         }
08664     }
08665     if(main->versionfile <= 232) {
08666         Tex *tex= main->tex.first;
08667         World *wrld= main->world.first;
08668         bScreen *sc;
08669         Scene *sce;
08670 
08671         while(tex) {
08672             if((tex->flag & (TEX_CHECKER_ODD+TEX_CHECKER_EVEN))==0) {
08673                 tex->flag |= TEX_CHECKER_ODD;
08674             }
08675             /* copied from kernel texture.c */
08676             if(tex->ns_outscale==0.0f) {
08677                 /* musgrave */
08678                 tex->mg_H = 1.0f;
08679                 tex->mg_lacunarity = 2.0f;
08680                 tex->mg_octaves = 2.0f;
08681                 tex->mg_offset = 1.0f;
08682                 tex->mg_gain = 1.0f;
08683                 tex->ns_outscale = 1.0f;
08684                 /* distnoise */
08685                 tex->dist_amount = 1.0f;
08686                 /* voronoi */
08687                 tex->vn_w1 = 1.0f;
08688                 tex->vn_mexp = 2.5f;
08689             }
08690             tex= tex->id.next;
08691         }
08692 
08693         while(wrld) {
08694             if(wrld->aodist==0.0f) {
08695                 wrld->aodist= 10.0f;
08696                 wrld->aobias= 0.05f;
08697             }
08698             if(wrld->aosamp==0) wrld->aosamp= 5;
08699             if(wrld->aoenergy==0.0f) wrld->aoenergy= 1.0f;
08700             wrld= wrld->id.next;
08701         }
08702 
08703 
08704         // new variable blockscale, for panels in any area, do again because new
08705         // areas didnt initialize it to 0.7 yet
08706         for (sc= main->screen.first; sc; sc= sc->id.next) {
08707             ScrArea *sa;
08708             for (sa= sc->areabase.first; sa; sa= sa->next) {
08709                 SpaceLink *sl;
08710                 for (sl= sa->spacedata.first; sl; sl= sl->next) {
08711                     if(sl->blockscale==0.0f) sl->blockscale= 0.7f;
08712 
08713                     /* added: 5x better zoom in for nla */
08714                     if(sl->spacetype==SPACE_NLA) {
08715                         SpaceNla *snla= (SpaceNla *)sl;
08716                         snla->v2d.maxzoom= 50;
08717                     }
08718                 }
08719             }
08720         }
08721         sce= main->scene.first;
08722         while(sce) {
08723             if(sce->r.ocres==0) sce->r.ocres= 64;
08724             sce= sce->id.next;
08725         }
08726 
08727     }
08728     if(main->versionfile <= 233) {
08729         bScreen *sc;
08730         Material *ma= main->mat.first;
08731         /* Object *ob= main->object.first; */
08732         
08733         while(ma) {
08734             if(ma->rampfac_col==0.0f) ma->rampfac_col= 1.0;
08735             if(ma->rampfac_spec==0.0f) ma->rampfac_spec= 1.0;
08736             if(ma->pr_lamp==0) ma->pr_lamp= 3;
08737             ma= ma->id.next;
08738         }
08739         
08740         /* this should have been done loooong before! */
08741 #if 0   /* deprecated in 2.5+ */
08742         while(ob) {
08743             if(ob->ipowin==0) ob->ipowin= ID_OB;
08744             ob= ob->id.next;
08745         }
08746 #endif
08747         for (sc= main->screen.first; sc; sc= sc->id.next) {
08748             ScrArea *sa;
08749             for (sa= sc->areabase.first; sa; sa= sa->next) {
08750                 SpaceLink *sl;
08751                 for (sl= sa->spacedata.first; sl; sl= sl->next) {
08752                     if(sl->spacetype==SPACE_VIEW3D) {
08753                         View3D *v3d= (View3D *)sl;
08754                         v3d->flag |= V3D_SELECT_OUTLINE;
08755                     }
08756                 }
08757             }
08758         }
08759     }
08760 
08761 
08762     
08763 
08764     if(main->versionfile <= 234) {
08765         World *wo;
08766         bScreen *sc;
08767         
08768         // force sumo engine to be active
08769         for (wo = main->world.first; wo; wo= wo->id.next) {
08770             if(wo->physicsEngine==0) wo->physicsEngine = 2;
08771         }
08772         
08773         for (sc= main->screen.first; sc; sc= sc->id.next) {
08774             ScrArea *sa;
08775             for (sa= sc->areabase.first; sa; sa= sa->next) {
08776                 SpaceLink *sl;
08777                 for (sl= sa->spacedata.first; sl; sl= sl->next) {
08778                     if(sl->spacetype==SPACE_VIEW3D) {
08779                         View3D *v3d= (View3D *)sl;
08780                         v3d->flag |= V3D_ZBUF_SELECT;
08781                     }
08782                     else if(sl->spacetype==SPACE_TEXT) {
08783                         SpaceText *st= (SpaceText *)sl;
08784                         if(st->tabnumber==0) st->tabnumber= 2;
08785                     }
08786                 }
08787             }
08788         }
08789     }
08790     if(main->versionfile <= 235) {
08791         Tex *tex= main->tex.first;
08792         Scene *sce= main->scene.first;
08793         Sequence *seq;
08794         Editing *ed;
08795         
08796         while(tex) {
08797             if(tex->nabla==0.0f) tex->nabla= 0.025f;
08798             tex= tex->id.next;
08799         }
08800         while(sce) {
08801             ed= sce->ed;
08802             if(ed) {
08803                 SEQ_BEGIN(sce->ed, seq) {
08804                     if(seq->type==SEQ_IMAGE || seq->type==SEQ_MOVIE)
08805                         seq->flag |= SEQ_MAKE_PREMUL;
08806                 }
08807                 SEQ_END
08808             }
08809             
08810             sce= sce->id.next;
08811         }
08812     }
08813     if(main->versionfile <= 236) {
08814         Object *ob;
08815         Camera *cam= main->camera.first;
08816         Material *ma;
08817         bScreen *sc;
08818 
08819         while(cam) {
08820             if(cam->ortho_scale==0.0f) {
08821                 cam->ortho_scale= 256.0f/cam->lens;
08822                 if(cam->type==CAM_ORTHO) printf("NOTE: ortho render has changed, tweak new Camera 'scale' value.\n");
08823             }
08824             cam= cam->id.next;
08825         }
08826         /* set manipulator type */
08827         /* force oops draw if depgraph was set*/
08828         /* set time line var */
08829         for (sc= main->screen.first; sc; sc= sc->id.next) {
08830             ScrArea *sa;
08831             for (sa= sc->areabase.first; sa; sa= sa->next) {
08832                 SpaceLink *sl;
08833                 for (sl= sa->spacedata.first; sl; sl= sl->next) {
08834                     if(sl->spacetype==SPACE_VIEW3D) {
08835                         View3D *v3d= (View3D *)sl;
08836                         if(v3d->twtype==0) v3d->twtype= V3D_MANIP_TRANSLATE;
08837                     }
08838                 }
08839             }
08840         }
08841         // init new shader vars
08842         for (ma= main->mat.first; ma; ma= ma->id.next) {
08843             if(ma->darkness==0.0f) {
08844                 ma->rms=0.1f;
08845                 ma->darkness=1.0f;
08846             }
08847         }
08848         
08849         /* softbody init new vars */
08850         for(ob= main->object.first; ob; ob= ob->id.next) {
08851             if(ob->soft) {
08852                 if(ob->soft->defgoal==0.0f) ob->soft->defgoal= 0.7f;
08853                 if(ob->soft->physics_speed==0.0f) ob->soft->physics_speed= 1.0f;
08854                 
08855                 if(ob->soft->interval==0) {
08856                     ob->soft->interval= 2;
08857                     ob->soft->sfra= 1;
08858                     ob->soft->efra= 100;
08859                 }
08860             }
08861             if(ob->soft && ob->soft->vertgroup==0) {
08862                 bDeformGroup *locGroup = defgroup_find_name(ob, "SOFTGOAL");
08863                 if (locGroup) {
08864                     /* retrieve index for that group */
08865                     ob->soft->vertgroup =  1 + BLI_findindex(&ob->defbase, locGroup);
08866                 }
08867             }
08868         }
08869     }
08870     if(main->versionfile <= 237) {
08871         bArmature *arm;
08872         bConstraint *con;
08873         Object *ob;
08874         Bone *bone;
08875         
08876         // armature recode checks 
08877         for(arm= main->armature.first; arm; arm= arm->id.next) {
08878             where_is_armature(arm);
08879 
08880             for(bone= arm->bonebase.first; bone; bone= bone->next)
08881                 do_version_bone_head_tail_237(bone);
08882         }
08883         for(ob= main->object.first; ob; ob= ob->id.next) {
08884             if(ob->parent) {
08885                 Object *parent= newlibadr(fd, lib, ob->parent);
08886                 if (parent && parent->type==OB_LATTICE)
08887                     ob->partype = PARSKEL;
08888             }
08889 
08890             // btw. armature_rebuild_pose is further only called on leave editmode
08891             if(ob->type==OB_ARMATURE) {
08892                 if(ob->pose)
08893                     ob->pose->flag |= POSE_RECALC;
08894                 ob->recalc |= OB_RECALC_OB|OB_RECALC_DATA|OB_RECALC_TIME;   // cannot call stuff now (pointers!), done in setup_app_data
08895 
08896                 /* new generic xray option */
08897                 arm= newlibadr(fd, lib, ob->data);
08898                 if(arm->flag & ARM_DRAWXRAY) {
08899                     ob->dtx |= OB_DRAWXRAY;
08900                 }
08901             } else if (ob->type==OB_MESH) {
08902                 Mesh *me = newlibadr(fd, lib, ob->data);
08903                 
08904                 if ((me->flag&ME_SUBSURF)) {
08905                     SubsurfModifierData *smd = (SubsurfModifierData*) modifier_new(eModifierType_Subsurf);
08906                     
08907                     smd->levels = MAX2(1, me->subdiv);
08908                     smd->renderLevels = MAX2(1, me->subdivr);
08909                     smd->subdivType = me->subsurftype;
08910                     
08911                     smd->modifier.mode = 0;
08912                     if (me->subdiv!=0)
08913                         smd->modifier.mode |= 1;
08914                     if (me->subdivr!=0)
08915                         smd->modifier.mode |= 2;
08916                     if (me->flag&ME_OPT_EDGES)
08917                         smd->flags |= eSubsurfModifierFlag_ControlEdges;
08918                     
08919                     BLI_addtail(&ob->modifiers, smd);
08920                     
08921                     modifier_unique_name(&ob->modifiers, (ModifierData*)smd);
08922                 }
08923             }
08924             
08925             // follow path constraint needs to set the 'path' option in curves...
08926             for(con=ob->constraints.first; con; con= con->next) {
08927                 if(con->type==CONSTRAINT_TYPE_FOLLOWPATH) {
08928                     bFollowPathConstraint *data = con->data;
08929                     Object *obc= newlibadr(fd, lib, data->tar);
08930                     
08931                     if(obc && obc->type==OB_CURVE) {
08932                         Curve *cu= newlibadr(fd, lib, obc->data);
08933                         if(cu) cu->flag |= CU_PATH;
08934                     }
08935                 }
08936             }
08937         }
08938     }
08939     if(main->versionfile <= 238) {
08940         Lattice *lt;
08941         Object *ob;
08942         bArmature *arm;
08943         Mesh *me;
08944         Key *key;
08945         Scene *sce= main->scene.first;
08946 
08947         while(sce){
08948             if(sce->toolsettings == NULL){
08949                 sce->toolsettings = MEM_callocN(sizeof(struct ToolSettings),"Tool Settings Struct");    
08950                 sce->toolsettings->cornertype=0;
08951                 sce->toolsettings->degr = 90; 
08952                 sce->toolsettings->step = 9;
08953                 sce->toolsettings->turn = 1;                
08954                 sce->toolsettings->extr_offs = 1; 
08955                 sce->toolsettings->doublimit = 0.001f;
08956                 sce->toolsettings->segments = 32;
08957                 sce->toolsettings->rings = 32;
08958                 sce->toolsettings->vertices = 32;
08959                 sce->toolsettings->editbutflag =1;
08960             }
08961             sce= sce->id.next;  
08962         }
08963 
08964         for (lt=main->latt.first; lt; lt=lt->id.next) {
08965             if (lt->fu==0.0f && lt->fv==0.0f && lt->fw==0.0f) {
08966                 calc_lat_fudu(lt->flag, lt->pntsu, &lt->fu, &lt->du);
08967                 calc_lat_fudu(lt->flag, lt->pntsv, &lt->fv, &lt->dv);
08968                 calc_lat_fudu(lt->flag, lt->pntsw, &lt->fw, &lt->dw);
08969             }
08970         }
08971 
08972         for(ob=main->object.first; ob; ob= ob->id.next) {
08973             ModifierData *md;
08974             PartEff *paf;
08975 
08976             for (md=ob->modifiers.first; md; md=md->next) {
08977                 if (md->type==eModifierType_Subsurf) {
08978                     SubsurfModifierData *smd = (SubsurfModifierData*) md;
08979 
08980                     smd->flags &= ~(eSubsurfModifierFlag_Incremental|eSubsurfModifierFlag_DebugIncr);
08981                 }
08982             }
08983 
08984             if ((ob->softflag&OB_SB_ENABLE) && !modifiers_findByType(ob, eModifierType_Softbody)) {
08985                 if (ob->softflag&OB_SB_POSTDEF) {
08986                     md = ob->modifiers.first;
08987 
08988                     while (md && modifierType_getInfo(md->type)->type==eModifierTypeType_OnlyDeform) {
08989                         md = md->next;
08990                     }
08991 
08992                     BLI_insertlinkbefore(&ob->modifiers, md, modifier_new(eModifierType_Softbody));
08993                 } else {
08994                     BLI_addhead(&ob->modifiers, modifier_new(eModifierType_Softbody));
08995                 }
08996 
08997                 ob->softflag &= ~OB_SB_ENABLE;
08998             }
08999             if(ob->pose) {
09000                 bPoseChannel *pchan;
09001                 bConstraint *con;
09002                 for(pchan= ob->pose->chanbase.first; pchan; pchan= pchan->next) {
09003                     // note, pchan->bone is also lib-link stuff
09004                     if (pchan->limitmin[0] == 0.0f && pchan->limitmax[0] == 0.0f) {
09005                         pchan->limitmin[0]= pchan->limitmin[1]= pchan->limitmin[2]= -180.0f;
09006                         pchan->limitmax[0]= pchan->limitmax[1]= pchan->limitmax[2]= 180.0f;
09007                         
09008                         for(con= pchan->constraints.first; con; con= con->next) {
09009                             if(con->type == CONSTRAINT_TYPE_KINEMATIC) {
09010                                 bKinematicConstraint *data = (bKinematicConstraint*)con->data;
09011                                 data->weight = 1.0f;
09012                                 data->orientweight = 1.0f;
09013                                 data->flag &= ~CONSTRAINT_IK_ROT;
09014                                 
09015                                 /* enforce conversion from old IK_TOPARENT to rootbone index */
09016                                 data->rootbone= -1;
09017                                 
09018                                 /* update_pose_etc handles rootbone==-1 */
09019                                 ob->pose->flag |= POSE_RECALC;
09020                             }   
09021                         }
09022                     }
09023                 }
09024             }
09025 
09026             paf = do_version_give_parteff_245(ob);
09027             if (paf) {
09028                 if(paf->disp == 0)
09029                     paf->disp = 100;
09030                 if(paf->speedtex == 0)
09031                     paf->speedtex = 8;
09032                 if(paf->omat == 0)
09033                     paf->omat = 1;
09034             }
09035         }
09036         
09037         for(arm=main->armature.first; arm; arm= arm->id.next) {
09038             bone_version_238(&arm->bonebase);
09039             arm->deformflag |= ARM_DEF_VGROUP;
09040         }
09041 
09042         for(me=main->mesh.first; me; me= me->id.next) {
09043             if (!me->medge) {
09044                 make_edges(me, 1);  /* 1 = use mface->edcode */
09045             } else {
09046                 mesh_strip_loose_faces(me);
09047             }
09048         }
09049         
09050         for(key= main->key.first; key; key= key->id.next) {
09051             KeyBlock *kb;
09052             int index= 1;
09053             
09054             /* trick to find out if we already introduced adrcode */
09055             for(kb= key->block.first; kb; kb= kb->next)
09056                 if(kb->adrcode) break;
09057             
09058             if(kb==NULL) {
09059                 for(kb= key->block.first; kb; kb= kb->next) {
09060                     if(kb==key->refkey) {
09061                         if(kb->name[0]==0)
09062                             strcpy(kb->name, "Basis");
09063                     }
09064                     else {
09065                         if (kb->name[0]==0) {
09066                             BLI_snprintf(kb->name, sizeof(kb->name), "Key %d", index);
09067                         }
09068                         kb->adrcode= index++;
09069                     }
09070                 }
09071             }
09072         }
09073     }
09074     if(main->versionfile <= 239) {
09075         bArmature *arm;
09076         Object *ob;
09077         Scene *sce= main->scene.first;
09078         Camera *cam= main->camera.first;
09079         Material *ma= main->mat.first;
09080         int set_passepartout= 0;
09081         
09082         /* deformflag is local in modifier now */
09083         for(ob=main->object.first; ob; ob= ob->id.next) {
09084             ModifierData *md;
09085             
09086             for (md=ob->modifiers.first; md; md=md->next) {
09087                 if (md->type==eModifierType_Armature) {
09088                     ArmatureModifierData *amd = (ArmatureModifierData*) md;
09089                     if(amd->object && amd->deformflag==0) {
09090                         Object *oba= newlibadr(fd, lib, amd->object);
09091                         arm= newlibadr(fd, lib, oba->data);
09092                         amd->deformflag= arm->deformflag;
09093                     }
09094                 }
09095             }
09096         }
09097         
09098         /* updating stepsize for ghost drawing */
09099         for(arm= main->armature.first; arm; arm= arm->id.next) {
09100             if (arm->ghostsize==0) arm->ghostsize=1;
09101             bone_version_239(&arm->bonebase);
09102             if(arm->layer==0) arm->layer= 1;
09103         }
09104         
09105         for(;sce;sce= sce->id.next) {
09106             /* make 'innervert' the default subdivide type, for backwards compat */
09107             sce->toolsettings->cornertype=1;
09108         
09109             if(sce->r.scemode & R_PASSEPARTOUT) {
09110                 set_passepartout= 1;
09111                 sce->r.scemode &= ~R_PASSEPARTOUT;
09112             }
09113             /* gauss is filter variable now */
09114             if(sce->r.mode & R_GAUSS) {
09115                 sce->r.filtertype= R_FILTER_GAUSS;
09116                 sce->r.mode &= ~R_GAUSS;
09117             }
09118         }
09119         
09120         for(;cam; cam= cam->id.next) {
09121             if(set_passepartout)
09122                 cam->flag |= CAM_SHOWPASSEPARTOUT;
09123             
09124             /* make sure old cameras have title safe on */
09125             if (!(cam->flag & CAM_SHOWTITLESAFE))
09126                 cam->flag |= CAM_SHOWTITLESAFE;
09127             
09128             /* set an appropriate camera passepartout alpha */
09129             if (!(cam->passepartalpha)) cam->passepartalpha = 0.2f;
09130         }
09131         
09132         for(; ma; ma= ma->id.next) {
09133             if(ma->strand_sta==0.0f) {
09134                 ma->strand_sta= ma->strand_end= 1.0f;
09135                 ma->mode |= MA_TANGENT_STR;
09136             }
09137             if(ma->mode & MA_TRACEBLE) ma->mode |= MA_SHADBUF;
09138         }
09139     }
09140     
09141     if(main->versionfile <= 241) {
09142         Object *ob;
09143         Tex *tex;
09144         Scene *sce;
09145         World *wo;
09146         Lamp *la;
09147         Material *ma;
09148         bArmature *arm;
09149         bNodeTree *ntree;
09150         
09151         for (wo = main->world.first; wo; wo= wo->id.next) {
09152             /* Migrate to Bullet for games, except for the NaN versions */
09153             /* People can still explicitly choose for Sumo (after 2.42 is out) */
09154             if(main->versionfile > 225)
09155                 wo->physicsEngine = WOPHY_BULLET;
09156             if(WO_AODIST == wo->aomode)
09157                 wo->aocolor= WO_AOPLAIN;
09158         }
09159         
09160         /* updating layers still */
09161         for(arm= main->armature.first; arm; arm= arm->id.next) {
09162             bone_version_239(&arm->bonebase);
09163             if(arm->layer==0) arm->layer= 1;
09164         }
09165         for(sce= main->scene.first; sce; sce= sce->id.next) {
09166             if(sce->audio.mixrate==0) sce->audio.mixrate= 44100;
09167 
09168             if(sce->r.xparts<2) sce->r.xparts= 4;
09169             if(sce->r.yparts<2) sce->r.yparts= 4;
09170             /* adds default layer */
09171             if(sce->r.layers.first==NULL)
09172                 scene_add_render_layer(sce, NULL);
09173             else {
09174                 SceneRenderLayer *srl;
09175                 /* new layer flag for sky, was default for solid */
09176                 for(srl= sce->r.layers.first; srl; srl= srl->next) {
09177                     if(srl->layflag & SCE_LAY_SOLID)
09178                         srl->layflag |= SCE_LAY_SKY;
09179                     srl->passflag &= (SCE_PASS_COMBINED|SCE_PASS_Z|SCE_PASS_NORMAL|SCE_PASS_VECTOR);
09180                 }
09181             }
09182             
09183             /* node version changes */
09184             if(sce->nodetree)
09185                 ntree_version_241(sce->nodetree);
09186 
09187             /* uv calculation options moved to toolsettings */
09188             if (sce->toolsettings->uvcalc_radius == 0.0f) {
09189                 sce->toolsettings->uvcalc_radius = 1.0f;
09190                 sce->toolsettings->uvcalc_cubesize = 1.0f;
09191                 sce->toolsettings->uvcalc_mapdir = 1;
09192                 sce->toolsettings->uvcalc_mapalign = 1;
09193                 sce->toolsettings->uvcalc_flag = UVCALC_FILLHOLES;
09194                 sce->toolsettings->unwrapper = 1;
09195             }
09196 
09197             if(sce->r.mode & R_PANORAMA) {
09198                 /* all these checks to ensure saved files with svn version keep working... */
09199                 if(sce->r.xsch < sce->r.ysch) {
09200                     Object *obc= newlibadr(fd, lib, sce->camera);
09201                     if(obc && obc->type==OB_CAMERA) {
09202                         Camera *cam= newlibadr(fd, lib, obc->data);
09203                         if(cam->lens>=10.0f) {
09204                             sce->r.xsch*= sce->r.xparts;
09205                             cam->lens*= (float)sce->r.ysch/(float)sce->r.xsch;
09206                         }
09207                     }
09208                 }
09209             }
09210         }
09211         
09212         for(ntree= main->nodetree.first; ntree; ntree= ntree->id.next)
09213             ntree_version_241(ntree);
09214         
09215         for(la= main->lamp.first; la; la= la->id.next)
09216             if(la->buffers==0)
09217                 la->buffers= 1;
09218         
09219         for(tex= main->tex.first; tex; tex= tex->id.next) {
09220             if(tex->env && tex->env->viewscale==0.0f)
09221                 tex->env->viewscale= 1.0f;
09222 //          tex->imaflag |= TEX_GAUSS_MIP;
09223         }
09224         
09225         /* for empty drawsize and drawtype */
09226         for(ob=main->object.first; ob; ob= ob->id.next) {
09227             if(ob->empty_drawsize==0.0f) {
09228                 ob->empty_drawtype = OB_ARROWS;
09229                 ob->empty_drawsize = 1.0;
09230             }
09231         }
09232         
09233         for(ma= main->mat.first; ma; ma= ma->id.next) {
09234             /* stucci returns intensity from now on */
09235             int a;
09236             for(a=0; a<MAX_MTEX; a++) {
09237                 if(ma->mtex[a] && ma->mtex[a]->tex) {
09238                     tex= newlibadr(fd, lib, ma->mtex[a]->tex);
09239                     if(tex && tex->type==TEX_STUCCI)
09240                         ma->mtex[a]->mapto &= ~(MAP_COL|MAP_SPEC|MAP_REF);
09241                 }
09242             }
09243             /* transmissivity defaults */
09244             if(ma->tx_falloff==0.0f) ma->tx_falloff= 1.0f;
09245         }
09246         
09247         /* during 2.41 images with this name were used for viewer node output, lets fix that */
09248         if(main->versionfile == 241) {
09249             Image *ima;
09250             for(ima= main->image.first; ima; ima= ima->id.next)
09251                 if(strcmp(ima->name, "Compositor")==0) {
09252                     strcpy(ima->id.name+2, "Viewer Node");
09253                     strcpy(ima->name, "Viewer Node");
09254                 }
09255         }
09256     }
09257         
09258     if(main->versionfile <= 242) {
09259         Scene *sce;
09260         bScreen *sc;
09261         Object *ob;
09262         Curve *cu;
09263         Material *ma;
09264         Mesh *me;
09265         Group *group;
09266         Nurb *nu;
09267         BezTriple *bezt;
09268         BPoint *bp;
09269         bNodeTree *ntree;
09270         int a;
09271         
09272         for(sc= main->screen.first; sc; sc= sc->id.next) {
09273             ScrArea *sa;
09274             sa= sc->areabase.first;
09275             while(sa) {
09276                 SpaceLink *sl;
09277 
09278                 for (sl= sa->spacedata.first; sl; sl= sl->next) {
09279                     if(sl->spacetype==SPACE_VIEW3D) {
09280                         View3D *v3d= (View3D*) sl;
09281                         if (v3d->gridsubdiv == 0)
09282                             v3d->gridsubdiv = 10;
09283                     }
09284                 }
09285                 sa = sa->next;
09286             }
09287         }
09288         
09289         for(sce= main->scene.first; sce; sce= sce->id.next) {
09290             if (sce->toolsettings->select_thresh == 0.0f)
09291                 sce->toolsettings->select_thresh= 0.01f;
09292             if (sce->toolsettings->clean_thresh == 0.0f) 
09293                 sce->toolsettings->clean_thresh = 0.1f;
09294                 
09295             if (sce->r.threads==0) {
09296                 if (sce->r.mode & R_THREADS)
09297                     sce->r.threads= 2;
09298                 else
09299                     sce->r.threads= 1;
09300             }
09301             if(sce->nodetree)
09302                 ntree_version_242(sce->nodetree);
09303         }
09304         
09305         for(ntree= main->nodetree.first; ntree; ntree= ntree->id.next)
09306             ntree_version_242(ntree);
09307         
09308         /* add default radius values to old curve points */
09309         for(cu= main->curve.first; cu; cu= cu->id.next) {
09310             for(nu= cu->nurb.first; nu; nu= nu->next) {
09311                 if (nu) {
09312                     if(nu->bezt) {
09313                         for(bezt=nu->bezt, a=0; a<nu->pntsu; a++, bezt++) {
09314                             if (!bezt->radius) bezt->radius= 1.0;
09315                         }
09316                     }
09317                     else if(nu->bp) {
09318                         for(bp=nu->bp, a=0; a<nu->pntsu*nu->pntsv; a++, bp++) {
09319                             if(!bp->radius) bp->radius= 1.0;
09320                         }
09321                     }
09322                 }
09323             }
09324         }
09325         
09326         for(ob = main->object.first; ob; ob= ob->id.next) {
09327             ModifierData *md;
09328             ListBase *list;
09329             list = &ob->constraints;
09330 
09331             /* check for already existing MinMax (floor) constraint
09332                and update the sticky flagging */
09333 
09334             if (list){
09335                 bConstraint *curcon;
09336                 for (curcon = list->first; curcon; curcon=curcon->next){
09337                     switch (curcon->type) {
09338                         case CONSTRAINT_TYPE_MINMAX:
09339                         {
09340                             bMinMaxConstraint *data = curcon->data;
09341                             if (data->sticky==1) 
09342                                 data->flag |= MINMAX_STICKY;
09343                             else 
09344                                 data->flag &= ~MINMAX_STICKY;
09345                         }
09346                             break;
09347                         case CONSTRAINT_TYPE_ROTLIKE:
09348                         {
09349                             bRotateLikeConstraint *data = curcon->data;
09350                             
09351                             /* version patch from buttons_object.c */
09352                             if(data->flag==0) 
09353                                 data->flag = ROTLIKE_X|ROTLIKE_Y|ROTLIKE_Z;
09354                         }
09355                             break;
09356                     }
09357                 }
09358             }
09359 
09360             if (ob->type == OB_ARMATURE) {
09361                 if (ob->pose){
09362                     bConstraint *curcon;
09363                     bPoseChannel *pchan;
09364                     for (pchan = ob->pose->chanbase.first; pchan; pchan=pchan->next){
09365                         for (curcon = pchan->constraints.first; curcon; curcon=curcon->next){
09366                             switch (curcon->type) {
09367                                 case CONSTRAINT_TYPE_MINMAX:
09368                                 {
09369                                     bMinMaxConstraint *data = curcon->data;
09370                                     if (data->sticky==1) 
09371                                         data->flag |= MINMAX_STICKY;
09372                                     else 
09373                                         data->flag &= ~MINMAX_STICKY;
09374                                 }
09375                                     break;
09376                                 case CONSTRAINT_TYPE_KINEMATIC:
09377                                 {
09378                                     bKinematicConstraint *data = curcon->data;
09379                                     if (!(data->flag & CONSTRAINT_IK_POS)) {
09380                                         data->flag |= CONSTRAINT_IK_POS;
09381                                         data->flag |= CONSTRAINT_IK_STRETCH;
09382                                     }
09383                                 }
09384                                     break;
09385                                 case CONSTRAINT_TYPE_ROTLIKE:
09386                                 {
09387                                     bRotateLikeConstraint *data = curcon->data;
09388                                     
09389                                     /* version patch from buttons_object.c */
09390                                     if(data->flag==0) 
09391                                         data->flag = ROTLIKE_X|ROTLIKE_Y|ROTLIKE_Z;
09392                                 }
09393                                     break;
09394                             }
09395                         }
09396                     }
09397                 }
09398             }
09399             
09400             /* copy old object level track settings to curve modifers */
09401             for (md=ob->modifiers.first; md; md=md->next) {
09402                 if (md->type==eModifierType_Curve) {
09403                     CurveModifierData *cmd = (CurveModifierData*) md;
09404 
09405                     if (cmd->defaxis == 0) cmd->defaxis = ob->trackflag+1;
09406                 }
09407             }
09408             
09409         }
09410         
09411         for(ma = main->mat.first; ma; ma= ma->id.next) {
09412             if(ma->shad_alpha==0.0f)
09413                 ma->shad_alpha= 1.0f;
09414             if(ma->nodetree)
09415                 ntree_version_242(ma->nodetree);
09416         }
09417 
09418         for(me=main->mesh.first; me; me=me->id.next)
09419             customdata_version_242(me);
09420         
09421         for(group= main->group.first; group; group= group->id.next)
09422             if(group->layer==0)
09423                 group->layer= (1<<20)-1;
09424         
09425         /* History fix (python?), shape key adrcode numbers have to be sorted */
09426         sort_shape_fix(main);
09427                 
09428         /* now, subversion control! */
09429         if(main->subversionfile < 3) {
09430             Image *ima;
09431             Tex *tex;
09432             
09433             /* Image refactor initialize */
09434             for(ima= main->image.first; ima; ima= ima->id.next) {
09435                 ima->source= IMA_SRC_FILE;
09436                 ima->type= IMA_TYPE_IMAGE;
09437                 
09438                 ima->gen_x= 256; ima->gen_y= 256;
09439                 ima->gen_type= 1;
09440                 
09441                 if(0==strncmp(ima->id.name+2, "Viewer Node", sizeof(ima->id.name)-2)) {
09442                     ima->source= IMA_SRC_VIEWER;
09443                     ima->type= IMA_TYPE_COMPOSITE;
09444                 }
09445                 if(0==strncmp(ima->id.name+2, "Render Result", sizeof(ima->id.name)-2)) {
09446                     ima->source= IMA_SRC_VIEWER;
09447                     ima->type= IMA_TYPE_R_RESULT;
09448                 }
09449                 
09450             }
09451             for(tex= main->tex.first; tex; tex= tex->id.next) {
09452                 if(tex->type==TEX_IMAGE && tex->ima) {
09453                     ima= newlibadr(fd, lib, tex->ima);
09454                     if(tex->imaflag & TEX_ANIM5_)
09455                         ima->source= IMA_SRC_MOVIE;
09456                     if(tex->imaflag & TEX_FIELDS_)
09457                         ima->flag |= IMA_FIELDS;
09458                     if(tex->imaflag & TEX_STD_FIELD_)
09459                         ima->flag |= IMA_STD_FIELD;
09460                 }
09461                 tex->iuser.frames= tex->frames;
09462                 tex->iuser.fie_ima= (char)tex->fie_ima;
09463                 tex->iuser.offset= tex->offset;
09464                 tex->iuser.sfra= tex->sfra;
09465                 tex->iuser.cycl= (tex->imaflag & TEX_ANIMCYCLIC_)!=0;
09466             }
09467             for(sce= main->scene.first; sce; sce= sce->id.next) {
09468                 if(sce->nodetree)
09469                     do_version_ntree_242_2(sce->nodetree);
09470             }
09471             for(ntree= main->nodetree.first; ntree; ntree= ntree->id.next)
09472                 do_version_ntree_242_2(ntree);
09473             for(ma = main->mat.first; ma; ma= ma->id.next)
09474                 if(ma->nodetree)
09475                     do_version_ntree_242_2(ma->nodetree);
09476             
09477             for(sc= main->screen.first; sc; sc= sc->id.next) {
09478                 ScrArea *sa;
09479                 for(sa= sc->areabase.first; sa; sa= sa->next) {
09480                     SpaceLink *sl;
09481                     for (sl= sa->spacedata.first; sl; sl= sl->next) {
09482                         if(sl->spacetype==SPACE_IMAGE)
09483                             ((SpaceImage *)sl)->iuser.fie_ima= 2;
09484                         else if(sl->spacetype==SPACE_VIEW3D) {
09485                             View3D *v3d= (View3D *)sl;
09486                             BGpic *bgpic;
09487                             for(bgpic= v3d->bgpicbase.first; bgpic; bgpic= bgpic->next)
09488                                 bgpic->iuser.fie_ima= 2;
09489                         }
09490                     }
09491                 }
09492             }
09493         }
09494         
09495         if(main->subversionfile < 4) {
09496             for(sce= main->scene.first; sce; sce= sce->id.next) {
09497                 sce->r.bake_mode= 1;    /* prevent to include render stuff here */
09498                 sce->r.bake_filter= 2;
09499                 sce->r.bake_osa= 5;
09500                 sce->r.bake_flag= R_BAKE_CLEAR;
09501             }
09502         }
09503 
09504         if(main->subversionfile < 5) {
09505             for(sce= main->scene.first; sce; sce= sce->id.next) {
09506                 /* improved triangle to quad conversion settings */
09507                 if(sce->toolsettings->jointrilimit==0.0f)
09508                     sce->toolsettings->jointrilimit= 0.8f;
09509             }
09510         }
09511     }
09512     if(main->versionfile <= 243) {
09513         Object *ob= main->object.first;
09514         Material *ma;
09515 
09516         for(ma=main->mat.first; ma; ma= ma->id.next) {
09517             if(ma->sss_scale==0.0f) {
09518                 ma->sss_radius[0]= 1.0f;
09519                 ma->sss_radius[1]= 1.0f;
09520                 ma->sss_radius[2]= 1.0f;
09521                 ma->sss_col[0]= 0.8f;
09522                 ma->sss_col[1]= 0.8f;
09523                 ma->sss_col[2]= 0.8f;
09524                 ma->sss_error= 0.05f;
09525                 ma->sss_scale= 0.1f;
09526                 ma->sss_ior= 1.3f;
09527                 ma->sss_colfac= 1.0f;
09528                 ma->sss_texfac= 0.0f;
09529             }
09530             if(ma->sss_front==0 && ma->sss_back==0) {
09531                 ma->sss_front= 1.0f;
09532                 ma->sss_back= 1.0f;
09533             }
09534             if(ma->sss_col[0]==0 && ma->sss_col[1]==0 && ma->sss_col[2]==0) {
09535                 ma->sss_col[0]= ma->r;
09536                 ma->sss_col[1]= ma->g;
09537                 ma->sss_col[2]= ma->b;
09538             }
09539         }
09540         
09541         for(; ob; ob= ob->id.next) {
09542             bDeformGroup *curdef;
09543             
09544             for(curdef= ob->defbase.first; curdef; curdef=curdef->next) {
09545                 /* replace an empty-string name with unique name */
09546                 if (curdef->name[0] == '\0') {
09547                     defgroup_unique_name(curdef, ob);
09548                 }
09549             }
09550 
09551             if(main->versionfile < 243 || main->subversionfile < 1) {
09552                 ModifierData *md;
09553 
09554                 /* translate old mirror modifier axis values to new flags */
09555                 for (md=ob->modifiers.first; md; md=md->next) {
09556                     if (md->type==eModifierType_Mirror) {
09557                         MirrorModifierData *mmd = (MirrorModifierData*) md;
09558 
09559                         switch(mmd->axis)
09560                         {
09561                         case 0:
09562                             mmd->flag |= MOD_MIR_AXIS_X;
09563                             break;
09564                         case 1:
09565                             mmd->flag |= MOD_MIR_AXIS_Y;
09566                             break;
09567                         case 2:
09568                             mmd->flag |= MOD_MIR_AXIS_Z;
09569                             break;
09570                         }
09571 
09572                         mmd->axis = 0;
09573                     }
09574                 }
09575             }
09576         }
09577         
09578         /* render layer added, this is not the active layer */
09579         if(main->versionfile <= 243 || main->subversionfile < 2) {
09580             Mesh *me;
09581             for(me=main->mesh.first; me; me=me->id.next)
09582                 customdata_version_243(me);
09583         }       
09584 
09585     }
09586     
09587     if(main->versionfile <= 244) {
09588         Scene *sce;
09589         bScreen *sc;
09590         Lamp *la;
09591         World *wrld;
09592         
09593         if(main->versionfile != 244 || main->subversionfile < 2) {
09594             for(sce= main->scene.first; sce; sce= sce->id.next)
09595                 sce->r.mode |= R_SSS;
09596 
09597             /* correct older action editors - incorrect scrolling */
09598             for(sc= main->screen.first; sc; sc= sc->id.next) {
09599                 ScrArea *sa;
09600                 sa= sc->areabase.first;
09601                 while(sa) {
09602                     SpaceLink *sl;
09603 
09604                     for (sl= sa->spacedata.first; sl; sl= sl->next) {
09605                         if(sl->spacetype==SPACE_ACTION) {
09606                             SpaceAction *saction= (SpaceAction*) sl;
09607                             
09608                             saction->v2d.tot.ymin= -1000.0;
09609                             saction->v2d.tot.ymax= 0.0;
09610                             
09611                             saction->v2d.cur.ymin= -75.0;
09612                             saction->v2d.cur.ymax= 5.0;
09613                         }
09614                     }
09615                     sa = sa->next;
09616                 }
09617             }
09618         }
09619         if (main->versionfile != 244 || main->subversionfile < 3) { 
09620             /* constraints recode version patch used to be here. Moved to 245 now... */
09621             
09622             
09623             for(wrld=main->world.first; wrld; wrld= wrld->id.next) {
09624                 if (wrld->mode & WO_AMB_OCC)
09625                     wrld->ao_samp_method = WO_AOSAMP_CONSTANT;
09626                 else
09627                     wrld->ao_samp_method = WO_AOSAMP_HAMMERSLEY;
09628                 
09629                 wrld->ao_adapt_thresh = 0.005f;
09630             }
09631             
09632             for(la=main->lamp.first; la; la= la->id.next) {
09633                 if (la->type == LA_AREA)
09634                     la->ray_samp_method = LA_SAMP_CONSTANT;
09635                 else
09636                     la->ray_samp_method = LA_SAMP_HALTON;
09637                 
09638                 la->adapt_thresh = 0.001f;
09639             }
09640         }
09641     }
09642     if(main->versionfile <= 245) {
09643         Scene *sce;
09644         Object *ob;
09645         Image *ima;
09646         Lamp *la;
09647         Material *ma;
09648         ParticleSettings *part;
09649         World *wrld;
09650         Mesh *me;
09651         bNodeTree *ntree;
09652         Tex *tex;
09653         ModifierData *md;
09654         ParticleSystem *psys;
09655         
09656         /* unless the file was created 2.44.3 but not 2.45, update the constraints */
09657         if ( !(main->versionfile==244 && main->subversionfile==3) &&
09658              ((main->versionfile<245) || (main->versionfile==245 && main->subversionfile==0)) ) 
09659         {
09660             for (ob = main->object.first; ob; ob= ob->id.next) {
09661                 ListBase *list;
09662                 list = &ob->constraints;
09663                 
09664                 /* fix up constraints due to constraint recode changes (originally at 2.44.3) */
09665                 if (list) {
09666                     bConstraint *curcon;
09667                     for (curcon = list->first; curcon; curcon=curcon->next) {
09668                         /* old CONSTRAINT_LOCAL check -> convert to CONSTRAINT_SPACE_LOCAL */
09669                         if (curcon->flag & 0x20) {
09670                             curcon->ownspace = CONSTRAINT_SPACE_LOCAL;
09671                             curcon->tarspace = CONSTRAINT_SPACE_LOCAL;
09672                         }
09673                         
09674                         switch (curcon->type) {
09675                             case CONSTRAINT_TYPE_LOCLIMIT:
09676                             {
09677                                 bLocLimitConstraint *data= (bLocLimitConstraint *)curcon->data;
09678                                 
09679                                 /* old limit without parent option for objects */
09680                                 if (data->flag2)
09681                                     curcon->ownspace = CONSTRAINT_SPACE_LOCAL;
09682                             }
09683                                 break;
09684                         }   
09685                     }
09686                 }
09687                 
09688                 /* correctly initialise constinv matrix */
09689                 unit_m4(ob->constinv);
09690                 
09691                 if (ob->type == OB_ARMATURE) {
09692                     if (ob->pose) {
09693                         bConstraint *curcon;
09694                         bPoseChannel *pchan;
09695                         
09696                         for (pchan = ob->pose->chanbase.first; pchan; pchan=pchan->next) {
09697                             /* make sure constraints are all up to date */
09698                             for (curcon = pchan->constraints.first; curcon; curcon=curcon->next) {
09699                                 /* old CONSTRAINT_LOCAL check -> convert to CONSTRAINT_SPACE_LOCAL */
09700                                 if (curcon->flag & 0x20) {
09701                                     curcon->ownspace = CONSTRAINT_SPACE_LOCAL;
09702                                     curcon->tarspace = CONSTRAINT_SPACE_LOCAL;
09703                                 }
09704                                 
09705                                 switch (curcon->type) {
09706                                     case CONSTRAINT_TYPE_ACTION:
09707                                     {
09708                                         bActionConstraint *data= (bActionConstraint *)curcon->data;
09709                                         
09710                                         /* 'data->local' used to mean that target was in local-space */
09711                                         if (data->local)
09712                                             curcon->tarspace = CONSTRAINT_SPACE_LOCAL;
09713                                     }                           
09714                                         break;
09715                                 }
09716                             }
09717                             
09718                             /* correctly initialise constinv matrix */
09719                             unit_m4(pchan->constinv);
09720                         }
09721                     }
09722                 }
09723             }
09724         }
09725         
09726         /* fix all versions before 2.45 */
09727         if (main->versionfile != 245) {
09728 
09729             /* repair preview from 242 - 244*/
09730             for(ima= main->image.first; ima; ima= ima->id.next) {
09731                 ima->preview = NULL;
09732             }
09733         }
09734 
09735         /* add point caches */
09736         for(ob=main->object.first; ob; ob=ob->id.next) {
09737             if(ob->soft && !ob->soft->pointcache)
09738                 ob->soft->pointcache= BKE_ptcache_add(&ob->soft->ptcaches);
09739 
09740             for(psys=ob->particlesystem.first; psys; psys=psys->next) {
09741                 if(psys->pointcache) {
09742                     if(psys->pointcache->flag & PTCACHE_BAKED && (psys->pointcache->flag & PTCACHE_DISK_CACHE)==0) {
09743                         printf("Old memory cache isn't supported for particles, so re-bake the simulation!\n");
09744                         psys->pointcache->flag &= ~PTCACHE_BAKED;
09745                     }
09746                 }
09747                 else
09748                     psys->pointcache= BKE_ptcache_add(&psys->ptcaches);
09749             }
09750 
09751             for(md=ob->modifiers.first; md; md=md->next) {
09752                 if(md->type==eModifierType_Cloth) {
09753                     ClothModifierData *clmd = (ClothModifierData*) md;
09754                     if(!clmd->point_cache)
09755                         clmd->point_cache= BKE_ptcache_add(&clmd->ptcaches);
09756                 }
09757             }
09758         }
09759 
09760         /* Copy over old per-level multires vertex data
09761            into a single vertex array in struct Multires */
09762         for(me = main->mesh.first; me; me=me->id.next) {
09763             if(me->mr && !me->mr->verts) {
09764                 MultiresLevel *lvl = me->mr->levels.last;
09765                 if(lvl) {
09766                     me->mr->verts = lvl->verts;
09767                     lvl->verts = NULL;
09768                     /* Don't need the other vert arrays */
09769                     for(lvl = lvl->prev; lvl; lvl = lvl->prev) {
09770                         MEM_freeN(lvl->verts);
09771                         lvl->verts = NULL;
09772                     }
09773                 }
09774             }
09775         }
09776         
09777         if (main->versionfile != 245 || main->subversionfile < 1) {
09778             for(la=main->lamp.first; la; la= la->id.next) {
09779                 if (la->mode & LA_QUAD) la->falloff_type = LA_FALLOFF_SLIDERS;
09780                 else la->falloff_type = LA_FALLOFF_INVLINEAR;
09781                 
09782                 if (la->curfalloff == NULL) {
09783                     la->curfalloff = curvemapping_add(1, 0.0f, 1.0f, 1.0f, 0.0f);
09784                     curvemapping_initialize(la->curfalloff);
09785                 }
09786             }
09787         }       
09788         
09789         for(ma=main->mat.first; ma; ma= ma->id.next) {
09790             if(ma->samp_gloss_mir == 0) {
09791                 ma->gloss_mir = ma->gloss_tra= 1.0f;
09792                 ma->aniso_gloss_mir = 1.0f;
09793                 ma->samp_gloss_mir = ma->samp_gloss_tra= 18;
09794                 ma->adapt_thresh_mir = ma->adapt_thresh_tra = 0.005f;
09795                 ma->dist_mir = 0.0f;
09796                 ma->fadeto_mir = MA_RAYMIR_FADETOSKY;
09797             }
09798 
09799             if(ma->strand_min == 0.0f)
09800                 ma->strand_min= 1.0f;
09801         }
09802 
09803         for(part=main->particle.first; part; part=part->id.next) {
09804             if(part->ren_child_nbr==0)
09805                 part->ren_child_nbr= part->child_nbr;
09806 
09807             if(part->simplify_refsize==0) {
09808                 part->simplify_refsize= 1920;
09809                 part->simplify_rate= 1.0f;
09810                 part->simplify_transition= 0.1f;
09811                 part->simplify_viewport= 0.8f;
09812             }
09813         }
09814 
09815         for(wrld=main->world.first; wrld; wrld= wrld->id.next) {
09816             if(wrld->ao_approx_error == 0.0f)
09817                 wrld->ao_approx_error= 0.25f;
09818         }
09819 
09820         for(sce= main->scene.first; sce; sce= sce->id.next) {
09821             if(sce->nodetree)
09822                 ntree_version_245(fd, lib, sce->nodetree);
09823 
09824             if(sce->r.simplify_shadowsamples == 0) {
09825                 sce->r.simplify_subsurf= 6;
09826                 sce->r.simplify_particles= 1.0f;
09827                 sce->r.simplify_shadowsamples= 16;
09828                 sce->r.simplify_aosss= 1.0f;
09829             }
09830 
09831             if(sce->r.cineongamma == 0) {
09832                 sce->r.cineonblack= 95;
09833                 sce->r.cineonwhite= 685;
09834                 sce->r.cineongamma= 1.7f;
09835             }
09836         }
09837 
09838         for(ntree=main->nodetree.first; ntree; ntree= ntree->id.next)
09839             ntree_version_245(fd, lib, ntree);
09840 
09841         /* fix for temporary flag changes during 245 cycle */
09842         for(ima= main->image.first; ima; ima= ima->id.next) {
09843             if(ima->flag & IMA_OLD_PREMUL) {
09844                 ima->flag &= ~IMA_OLD_PREMUL;
09845                 ima->flag |= IMA_DO_PREMUL;
09846             }
09847         }
09848 
09849         for(tex=main->tex.first; tex; tex=tex->id.next) {
09850             if(tex->iuser.flag & IMA_OLD_PREMUL) {
09851                 tex->iuser.flag &= ~IMA_OLD_PREMUL;
09852                 tex->iuser.flag |= IMA_DO_PREMUL;
09853 
09854             }
09855 
09856             ima= newlibadr(fd, lib, tex->ima);
09857             if(ima && (tex->iuser.flag & IMA_DO_PREMUL)) { 
09858                 ima->flag &= ~IMA_OLD_PREMUL;
09859                 ima->flag |= IMA_DO_PREMUL;
09860             }
09861         }
09862     }
09863     
09864     /* sanity check for skgen
09865      * */
09866     {
09867         Scene *sce;
09868         for(sce=main->scene.first; sce; sce = sce->id.next)
09869         {
09870             if (sce->toolsettings->skgen_subdivisions[0] == sce->toolsettings->skgen_subdivisions[1] ||
09871                 sce->toolsettings->skgen_subdivisions[0] == sce->toolsettings->skgen_subdivisions[2] ||
09872                 sce->toolsettings->skgen_subdivisions[1] == sce->toolsettings->skgen_subdivisions[2])
09873             {
09874                     sce->toolsettings->skgen_subdivisions[0] = SKGEN_SUB_CORRELATION;
09875                     sce->toolsettings->skgen_subdivisions[1] = SKGEN_SUB_LENGTH;
09876                     sce->toolsettings->skgen_subdivisions[2] = SKGEN_SUB_ANGLE;
09877             }
09878         }
09879     }
09880     
09881 
09882     if ((main->versionfile < 245) || (main->versionfile == 245 && main->subversionfile < 2)) {
09883         Image *ima;
09884 
09885         /* initialize 1:1 Aspect */
09886         for(ima= main->image.first; ima; ima= ima->id.next) {
09887             ima->aspx = ima->aspy = 1.0f;               
09888         }
09889 
09890     }
09891 
09892     if ((main->versionfile < 245) || (main->versionfile == 245 && main->subversionfile < 4)) {
09893         bArmature *arm;
09894         ModifierData *md;
09895         Object *ob;
09896         
09897         for(arm= main->armature.first; arm; arm= arm->id.next)
09898             arm->deformflag |= ARM_DEF_B_BONE_REST;
09899         
09900         for(ob = main->object.first; ob; ob= ob->id.next) {
09901             for(md=ob->modifiers.first; md; md=md->next) {
09902                 if(md->type==eModifierType_Armature)
09903                     ((ArmatureModifierData*)md)->deformflag |= ARM_DEF_B_BONE_REST;
09904             }
09905         }
09906     }
09907 
09908     if ((main->versionfile < 245) || (main->versionfile == 245 && main->subversionfile < 5)) {
09909         /* foreground color needs to be somthing other then black */
09910         Scene *sce;
09911         for(sce= main->scene.first; sce; sce=sce->id.next) {
09912             sce->r.fg_stamp[0] = sce->r.fg_stamp[1] = sce->r.fg_stamp[2] = 0.8f;
09913             sce->r.fg_stamp[3] = 1.0f; /* dont use text alpha yet */
09914             sce->r.bg_stamp[3] = 0.25f; /* make sure the background has full alpha */
09915         }
09916     }
09917 
09918     
09919     if ((main->versionfile < 245) || (main->versionfile == 245 && main->subversionfile < 6)) {
09920         Scene *sce;
09921         /* fix frs_sec_base */
09922         for(sce= main->scene.first; sce; sce= sce->id.next) {
09923             if (sce->r.frs_sec_base == 0) {
09924                 sce->r.frs_sec_base = 1;
09925             }
09926         }
09927     }
09928     
09929     if ((main->versionfile < 245) || (main->versionfile == 245 && main->subversionfile < 7)) {
09930         Object *ob;
09931         bPoseChannel *pchan;
09932         bConstraint *con;
09933         bConstraintTarget *ct;
09934         
09935         for (ob = main->object.first; ob; ob= ob->id.next) {
09936             if (ob->pose) {
09937                 for (pchan=ob->pose->chanbase.first; pchan; pchan=pchan->next) {
09938                     for (con=pchan->constraints.first; con; con=con->next) {
09939                         if (con->type == CONSTRAINT_TYPE_PYTHON) {
09940                             bPythonConstraint *data= (bPythonConstraint *)con->data;
09941                             if (data->tar) {
09942                                 /* version patching needs to be done */
09943                                 ct= MEM_callocN(sizeof(bConstraintTarget), "PyConTarget");
09944                                 
09945                                 ct->tar = data->tar;
09946                                 BLI_strncpy(ct->subtarget, data->subtarget, sizeof(ct->subtarget));
09947                                 ct->space = con->tarspace;
09948                                 
09949                                 BLI_addtail(&data->targets, ct);
09950                                 data->tarnum++;
09951                                 
09952                                 /* clear old targets to avoid problems */
09953                                 data->tar = NULL;
09954                                 data->subtarget[0]= '\0';
09955                             }
09956                         }
09957                         else if (con->type == CONSTRAINT_TYPE_LOCLIKE) {
09958                             bLocateLikeConstraint *data= (bLocateLikeConstraint *)con->data;
09959                             
09960                             /* new headtail functionality makes Bone-Tip function obsolete */
09961                             if (data->flag & LOCLIKE_TIP)
09962                                 con->headtail = 1.0f;
09963                         }
09964                     }
09965                 }
09966             }
09967             
09968             for (con=ob->constraints.first; con; con=con->next) {
09969                 if (con->type==CONSTRAINT_TYPE_PYTHON) {
09970                     bPythonConstraint *data= (bPythonConstraint *)con->data;
09971                     if (data->tar) {
09972                         /* version patching needs to be done */
09973                         ct= MEM_callocN(sizeof(bConstraintTarget), "PyConTarget");
09974                         
09975                         ct->tar = data->tar;
09976                         BLI_strncpy(ct->subtarget, data->subtarget, sizeof(ct->subtarget));
09977                         ct->space = con->tarspace;
09978                         
09979                         BLI_addtail(&data->targets, ct);
09980                         data->tarnum++;
09981                         
09982                         /* clear old targets to avoid problems */
09983                         data->tar = NULL;
09984                         data->subtarget[0]= '\0';
09985                     }
09986                 }
09987                 else if (con->type == CONSTRAINT_TYPE_LOCLIKE) {
09988                     bLocateLikeConstraint *data= (bLocateLikeConstraint *)con->data;
09989                     
09990                     /* new headtail functionality makes Bone-Tip function obsolete */
09991                     if (data->flag & LOCLIKE_TIP)
09992                         con->headtail = 1.0f;
09993                 }
09994             }
09995 
09996             if(ob->soft && ob->soft->keys) {
09997                 SoftBody *sb = ob->soft;
09998                 int k;
09999 
10000                 for(k=0; k<sb->totkey; k++) {
10001                     if(sb->keys[k])
10002                         MEM_freeN(sb->keys[k]);
10003                 }
10004 
10005                 MEM_freeN(sb->keys);
10006 
10007                 sb->keys = NULL;
10008                 sb->totkey = 0;
10009             }
10010         }
10011     }
10012 
10013     if ((main->versionfile < 245) || (main->versionfile == 245 && main->subversionfile < 8)) {
10014         Scene *sce;
10015         Object *ob;
10016         PartEff *paf=NULL;
10017 
10018         for(ob = main->object.first; ob; ob= ob->id.next) {
10019             if(ob->soft && ob->soft->keys) {
10020                 SoftBody *sb = ob->soft;
10021                 int k;
10022 
10023                 for(k=0; k<sb->totkey; k++) {
10024                     if(sb->keys[k])
10025                         MEM_freeN(sb->keys[k]);
10026                 }
10027 
10028                 MEM_freeN(sb->keys);
10029 
10030                 sb->keys = NULL;
10031                 sb->totkey = 0;
10032             }
10033 
10034             /* convert old particles to new system */
10035             if((paf = do_version_give_parteff_245(ob))) {
10036                 ParticleSystem *psys;
10037                 ModifierData *md;
10038                 ParticleSystemModifierData *psmd;
10039                 ParticleSettings *part;
10040 
10041                 /* create new particle system */
10042                 psys = MEM_callocN(sizeof(ParticleSystem), "particle_system");
10043                 psys->pointcache = BKE_ptcache_add(&psys->ptcaches);
10044 
10045                 part = psys->part = psys_new_settings("ParticleSettings", main);
10046                 
10047                 /* needed for proper libdata lookup */
10048                 oldnewmap_insert(fd->libmap, psys->part, psys->part, 0);
10049                 part->id.lib= ob->id.lib;
10050 
10051                 part->id.us--;
10052                 part->id.flag |= (ob->id.flag & LIB_NEEDLINK);
10053                 
10054                 psys->totpart=0;
10055                 psys->flag= PSYS_ENABLED|PSYS_CURRENT;
10056 
10057                 BLI_addtail(&ob->particlesystem, psys);
10058 
10059                 md= modifier_new(eModifierType_ParticleSystem);
10060                 BLI_snprintf(md->name, sizeof(md->name), "ParticleSystem %i", BLI_countlist(&ob->particlesystem));
10061                 psmd= (ParticleSystemModifierData*) md;
10062                 psmd->psys=psys;
10063                 BLI_addtail(&ob->modifiers, md);
10064 
10065                 /* convert settings from old particle system */
10066                 /* general settings */
10067                 part->totpart = MIN2(paf->totpart, 100000);
10068                 part->sta = paf->sta;
10069                 part->end = paf->end;
10070                 part->lifetime = paf->lifetime;
10071                 part->randlife = paf->randlife;
10072                 psys->seed = paf->seed;
10073                 part->disp = paf->disp;
10074                 part->omat = paf->mat[0];
10075                 part->hair_step = paf->totkey;
10076 
10077                 part->eff_group = paf->group;
10078 
10079                 /* old system didn't interpolate between keypoints at render time */
10080                 part->draw_step = part->ren_step = 0;
10081 
10082                 /* physics */
10083                 part->normfac = paf->normfac * 25.0f;
10084                 part->obfac = paf->obfac;
10085                 part->randfac = paf->randfac * 25.0f;
10086                 part->dampfac = paf->damp;
10087                 copy_v3_v3(part->acc, paf->force);
10088 
10089                 /* flags */
10090                 if(paf->stype & PAF_VECT) {
10091                     if(paf->flag & PAF_STATIC) {
10092                         /* new hair lifetime is always 100.0f */
10093                         float fac = paf->lifetime / 100.0f;
10094 
10095                         part->draw_as = PART_DRAW_PATH;
10096                         part->type = PART_HAIR;
10097                         psys->recalc |= PSYS_RECALC_REDO;
10098 
10099                         part->normfac *= fac;
10100                         part->randfac *= fac;
10101                     }
10102                     else {
10103                         part->draw_as = PART_DRAW_LINE;
10104                         part->draw |= PART_DRAW_VEL_LENGTH;
10105                         part->draw_line[1] = 0.04f;
10106                     }
10107                 }
10108 
10109                 part->rotmode = PART_ROT_VEL;
10110                 
10111                 part->flag |= (paf->flag & PAF_BSPLINE) ? PART_HAIR_BSPLINE : 0;
10112                 part->flag |= (paf->flag & PAF_TRAND) ? PART_TRAND : 0;
10113                 part->flag |= (paf->flag & PAF_EDISTR) ? PART_EDISTR : 0;
10114                 part->flag |= (paf->flag & PAF_UNBORN) ? PART_UNBORN : 0;
10115                 part->flag |= (paf->flag & PAF_DIED) ? PART_DIED : 0;
10116                 part->from |= (paf->flag & PAF_FACE) ? PART_FROM_FACE : 0;
10117                 part->draw |= (paf->flag & PAF_SHOWE) ? PART_DRAW_EMITTER : 0;
10118 
10119                 psys->vgroup[PSYS_VG_DENSITY] = paf->vertgroup;
10120                 psys->vgroup[PSYS_VG_VEL] = paf->vertgroup_v;
10121                 psys->vgroup[PSYS_VG_LENGTH] = paf->vertgroup_v;
10122 
10123                 /* dupliobjects */
10124                 if(ob->transflag & OB_DUPLIVERTS) {
10125                     Object *dup = main->object.first;
10126 
10127                     for(; dup; dup= dup->id.next) {
10128                         if(ob == newlibadr(fd, lib, dup->parent)) {
10129                             part->dup_ob = dup;
10130                             ob->transflag |= OB_DUPLIPARTS;
10131                             ob->transflag &= ~OB_DUPLIVERTS;
10132 
10133                             part->draw_as = PART_DRAW_OB;
10134 
10135                             /* needed for proper libdata lookup */
10136                             oldnewmap_insert(fd->libmap, dup, dup, 0);
10137                         }
10138                     }
10139                 }
10140 
10141                 
10142                 {
10143                     FluidsimModifierData *fluidmd = (FluidsimModifierData *)modifiers_findByType(ob, eModifierType_Fluidsim);
10144                     if(fluidmd && fluidmd->fss && fluidmd->fss->type == OB_FLUIDSIM_PARTICLE)
10145                         part->type = PART_FLUID;
10146                 }
10147 
10148                 do_version_free_effects_245(&ob->effect);
10149 
10150                 printf("Old particle system converted to new system.\n");
10151             }
10152         }
10153 
10154         for(sce= main->scene.first; sce; sce=sce->id.next) {
10155             ParticleEditSettings *pset= &sce->toolsettings->particle;
10156             int a;
10157 
10158             if(pset->brush[0].size == 0) {
10159                 pset->flag= PE_KEEP_LENGTHS|PE_LOCK_FIRST|PE_DEFLECT_EMITTER;
10160                 pset->emitterdist= 0.25f;
10161                 pset->totrekey= 5;
10162                 pset->totaddkey= 5;
10163                 pset->brushtype= PE_BRUSH_NONE;
10164 
10165                 for(a=0; a<PE_TOT_BRUSH; a++) {
10166                     pset->brush[a].strength= 50;
10167                     pset->brush[a].size= 50;
10168                     pset->brush[a].step= 10;
10169                 }
10170 
10171                 pset->brush[PE_BRUSH_CUT].strength= 100;
10172             }
10173         }
10174     }
10175     if ((main->versionfile < 245) || (main->versionfile == 245 && main->subversionfile < 9)) {
10176         Material *ma;
10177         int a;
10178 
10179         for(ma=main->mat.first; ma; ma= ma->id.next)
10180             if(ma->mode & MA_NORMAP_TANG)
10181                 for(a=0; a<MAX_MTEX; a++)
10182                     if(ma->mtex[a] && ma->mtex[a]->tex)
10183                         ma->mtex[a]->normapspace = MTEX_NSPACE_TANGENT;
10184     }
10185     
10186     if ((main->versionfile < 245) || (main->versionfile == 245 && main->subversionfile < 10)) {
10187         Object *ob;
10188         
10189         /* dupliface scale */
10190         for(ob= main->object.first; ob; ob= ob->id.next)
10191             ob->dupfacesca = 1.0f;
10192     }
10193     
10194     if ((main->versionfile < 245) || (main->versionfile == 245 && main->subversionfile < 11)) {
10195         Object *ob;
10196         bActionStrip *strip;
10197         
10198         /* nla-strips - scale */        
10199         for (ob= main->object.first; ob; ob= ob->id.next) {
10200             for (strip= ob->nlastrips.first; strip; strip= strip->next) {
10201                 float length, actlength, repeat;
10202                 
10203                 if (strip->flag & ACTSTRIP_USESTRIDE)
10204                     repeat= 1.0f;
10205                 else
10206                     repeat= strip->repeat;
10207                 
10208                 length = strip->end-strip->start;
10209                 if (length == 0.0f) length= 1.0f;
10210                 actlength = strip->actend-strip->actstart;
10211                 
10212                 strip->scale = length / (repeat * actlength);
10213                 if (strip->scale == 0.0f) strip->scale= 1.0f;
10214             }   
10215             if(ob->soft){
10216                 ob->soft->inpush =  ob->soft->inspring;
10217                 ob->soft->shearstiff = 1.0f; 
10218             }
10219         }
10220     }
10221 
10222     if ((main->versionfile < 245) || (main->versionfile == 245 && main->subversionfile < 14)) {
10223         Scene *sce;
10224         Sequence *seq;
10225         
10226         for(sce=main->scene.first; sce; sce=sce->id.next) {
10227             SEQ_BEGIN(sce->ed, seq) {
10228                 if (seq->blend_mode == 0)
10229                     seq->blend_opacity = 100.0f;
10230             }
10231             SEQ_END
10232         }
10233     }
10234     
10235     /*fix broken group lengths in id properties*/
10236     if ((main->versionfile < 245) || (main->versionfile == 245 && main->subversionfile < 15)) {
10237         idproperties_fix_group_lengths(main->scene);
10238         idproperties_fix_group_lengths(main->library);
10239         idproperties_fix_group_lengths(main->object);
10240         idproperties_fix_group_lengths(main->mesh);
10241         idproperties_fix_group_lengths(main->curve);
10242         idproperties_fix_group_lengths(main->mball);
10243         idproperties_fix_group_lengths(main->mat);
10244         idproperties_fix_group_lengths(main->tex);
10245         idproperties_fix_group_lengths(main->image);
10246         idproperties_fix_group_lengths(main->latt);
10247         idproperties_fix_group_lengths(main->lamp);
10248         idproperties_fix_group_lengths(main->camera);
10249         idproperties_fix_group_lengths(main->ipo);
10250         idproperties_fix_group_lengths(main->key);
10251         idproperties_fix_group_lengths(main->world);
10252         idproperties_fix_group_lengths(main->screen);
10253         idproperties_fix_group_lengths(main->script);
10254         idproperties_fix_group_lengths(main->vfont);
10255         idproperties_fix_group_lengths(main->text);
10256         idproperties_fix_group_lengths(main->sound);
10257         idproperties_fix_group_lengths(main->group);
10258         idproperties_fix_group_lengths(main->armature);
10259         idproperties_fix_group_lengths(main->action);
10260         idproperties_fix_group_lengths(main->nodetree);
10261         idproperties_fix_group_lengths(main->brush);
10262         idproperties_fix_group_lengths(main->particle);     
10263     }
10264 
10265     /* sun/sky */
10266     if(main->versionfile < 246) {
10267         Object *ob;
10268         bActuator *act;
10269 
10270         /* dRot actuator change direction in 2.46 */
10271         for(ob = main->object.first; ob; ob= ob->id.next) {
10272             for(act= ob->actuators.first; act; act= act->next) {
10273                 if (act->type == ACT_OBJECT) {
10274                     bObjectActuator *ba= act->data;
10275 
10276                     ba->drot[0] = -ba->drot[0];
10277                     ba->drot[1] = -ba->drot[1];
10278                     ba->drot[2] = -ba->drot[2];
10279                 }
10280             }
10281         }
10282     }
10283     
10284     // convert fluids to modifier
10285     if(main->versionfile < 246 || (main->versionfile == 246 && main->subversionfile < 1))
10286     {
10287         Object *ob;
10288         
10289         for(ob = main->object.first; ob; ob= ob->id.next) {
10290             if(ob->fluidsimSettings)
10291             {
10292                 FluidsimModifierData *fluidmd = (FluidsimModifierData *)modifier_new(eModifierType_Fluidsim);
10293                 BLI_addhead(&ob->modifiers, (ModifierData *)fluidmd);
10294                 
10295                 MEM_freeN(fluidmd->fss);
10296                 fluidmd->fss = MEM_dupallocN(ob->fluidsimSettings);
10297                 fluidmd->fss->ipo = newlibadr_us(fd, ob->id.lib, ob->fluidsimSettings->ipo);
10298                 MEM_freeN(ob->fluidsimSettings);
10299                 
10300                 fluidmd->fss->lastgoodframe = INT_MAX;
10301                 fluidmd->fss->flag = 0;
10302                 fluidmd->fss->meshVelocities = NULL;
10303             }
10304         }
10305     }
10306     
10307 
10308     if(main->versionfile < 246 || (main->versionfile == 246 && main->subversionfile < 1)) {
10309         Mesh *me;
10310 
10311         for(me=main->mesh.first; me; me= me->id.next)
10312             alphasort_version_246(fd, lib, me);
10313     }
10314     
10315     if(main->versionfile < 246 || (main->versionfile == 246 && main->subversionfile < 1)){
10316         Object *ob;
10317         for(ob = main->object.first; ob; ob= ob->id.next) {
10318             if(ob->pd && (ob->pd->forcefield == PFIELD_WIND))
10319                 ob->pd->f_noise = 0.0f;
10320         }
10321     }
10322 
10323     if (main->versionfile < 247 || (main->versionfile == 247 && main->subversionfile < 2)){
10324         Object *ob;
10325         for(ob = main->object.first; ob; ob= ob->id.next) {
10326             ob->gameflag |= OB_COLLISION;
10327             ob->margin = 0.06f;
10328         }
10329     }
10330 
10331     if (main->versionfile < 247 || (main->versionfile == 247 && main->subversionfile < 3)){
10332         Object *ob;
10333         for(ob = main->object.first; ob; ob= ob->id.next) {
10334             // Starting from subversion 3, ACTOR is a separate feature.
10335             // Before it was conditioning all the other dynamic flags
10336             if (!(ob->gameflag & OB_ACTOR))
10337                 ob->gameflag &= ~(OB_GHOST|OB_DYNAMIC|OB_RIGID_BODY|OB_SOFT_BODY|OB_COLLISION_RESPONSE);
10338             /* suitable default for older files */
10339         }
10340     }
10341 
10342     if (main->versionfile < 247 || (main->versionfile == 247 && main->subversionfile < 5)) {
10343         Lamp *la= main->lamp.first;
10344         for(; la; la= la->id.next) {
10345             la->skyblendtype= MA_RAMP_ADD;
10346             la->skyblendfac= 1.0f;
10347         }
10348     }
10349     
10350     /* set the curve radius interpolation to 2.47 default - easy */
10351     if (main->versionfile < 247 || (main->versionfile == 247 && main->subversionfile < 6)) {
10352         Curve *cu;
10353         Nurb *nu;
10354         
10355         for(cu= main->curve.first; cu; cu= cu->id.next) {
10356             for(nu= cu->nurb.first; nu; nu= nu->next) {
10357                 if (nu) {
10358                     nu->radius_interp = 3;
10359                     
10360                     /* resolu and resolv are now used differently for surfaces
10361                      * rather than using the resolution to define the entire number of divisions,
10362                      * use it for the number of divisions per segment
10363                      */
10364                     if (nu->pntsv > 1) {
10365                         nu->resolu = MAX2( 1, (int)(((float)nu->resolu / (float)nu->pntsu)+0.5f) );
10366                         nu->resolv = MAX2( 1, (int)(((float)nu->resolv / (float)nu->pntsv)+0.5f) );
10367                     }
10368                 }
10369             }
10370         }
10371     }
10372     /* direction constraint actuators were always local in previous version */
10373     if (main->versionfile < 247 || (main->versionfile == 247 && main->subversionfile < 7)) {
10374         bActuator *act;
10375         Object *ob;
10376         
10377         for(ob = main->object.first; ob; ob= ob->id.next) {
10378             for(act= ob->actuators.first; act; act= act->next) {
10379                 if (act->type == ACT_CONSTRAINT) {
10380                     bConstraintActuator *coa = act->data;
10381                     if (coa->type == ACT_CONST_TYPE_DIST) {
10382                         coa->flag |= ACT_CONST_LOCAL;
10383                     }
10384                 }
10385             }
10386         }
10387     }
10388 
10389     if (main->versionfile < 247 || (main->versionfile == 247 && main->subversionfile < 9)) {
10390         Lamp *la= main->lamp.first;
10391         for(; la; la= la->id.next) {
10392             la->sky_exposure= 1.0f;
10393         }
10394     }
10395     
10396     /* BGE message actuators needed OB prefix, very confusing */
10397     if (main->versionfile < 247 || (main->versionfile == 247 && main->subversionfile < 10)) {
10398         bActuator *act;
10399         Object *ob;
10400         
10401         for(ob = main->object.first; ob; ob= ob->id.next) {
10402             for(act= ob->actuators.first; act; act= act->next) {
10403                 if (act->type == ACT_MESSAGE) {
10404                     bMessageActuator *msgAct = (bMessageActuator *) act->data;
10405                     if (BLI_strnlen(msgAct->toPropName, 3) > 2) {
10406                         /* strip first 2 chars, would have only worked if these were OB anyway */
10407                         memmove( msgAct->toPropName, msgAct->toPropName+2, sizeof(msgAct->toPropName)-2 );
10408                     } else {
10409                         msgAct->toPropName[0] = '\0';
10410                     }
10411                 }
10412             }
10413         }
10414     }
10415 
10416     if (main->versionfile < 248) {
10417         Lamp *la;
10418 
10419         for(la=main->lamp.first; la; la= la->id.next) {
10420             if(la->atm_turbidity == 0.0f) {
10421                 la->sun_effect_type = 0;
10422                 la->horizon_brightness = 1.0f;
10423                 la->spread = 1.0f;
10424                 la->sun_brightness = 1.0f;
10425                 la->sun_size = 1.0f;
10426                 la->backscattered_light = 1.0f;
10427                 la->atm_turbidity = 2.0f;
10428                 la->atm_inscattering_factor = 1.0f;
10429                 la->atm_extinction_factor = 1.0f;
10430                 la->atm_distance_factor = 1.0f;
10431                 la->sun_intensity = 1.0f;
10432             }
10433         }
10434     }
10435 
10436     if (main->versionfile < 248 || (main->versionfile == 248 && main->subversionfile < 2)) {
10437         Scene *sce;
10438         
10439         /* Note, these will need to be added for painting */
10440         for (sce= main->scene.first; sce; sce= sce->id.next) {
10441             sce->toolsettings->imapaint.seam_bleed = 2;
10442             sce->toolsettings->imapaint.normal_angle = 80;
10443 
10444             /* initialize skeleton generation toolsettings */
10445             sce->toolsettings->skgen_resolution = 250;
10446             sce->toolsettings->skgen_threshold_internal     = 0.1f;
10447             sce->toolsettings->skgen_threshold_external     = 0.1f;
10448             sce->toolsettings->skgen_angle_limit            = 30.0f;
10449             sce->toolsettings->skgen_length_ratio           = 1.3f;
10450             sce->toolsettings->skgen_length_limit           = 1.5f;
10451             sce->toolsettings->skgen_correlation_limit      = 0.98f;
10452             sce->toolsettings->skgen_symmetry_limit         = 0.1f;
10453             sce->toolsettings->skgen_postpro = SKGEN_SMOOTH;
10454             sce->toolsettings->skgen_postpro_passes = 3;
10455             sce->toolsettings->skgen_options = SKGEN_FILTER_INTERNAL|SKGEN_FILTER_EXTERNAL|SKGEN_FILTER_SMART|SKGEN_SUB_CORRELATION|SKGEN_HARMONIC;
10456             sce->toolsettings->skgen_subdivisions[0] = SKGEN_SUB_CORRELATION;
10457             sce->toolsettings->skgen_subdivisions[1] = SKGEN_SUB_LENGTH;
10458             sce->toolsettings->skgen_subdivisions[2] = SKGEN_SUB_ANGLE;
10459 
10460             
10461             sce->toolsettings->skgen_retarget_angle_weight = 1.0f;
10462             sce->toolsettings->skgen_retarget_length_weight = 1.0f;
10463             sce->toolsettings->skgen_retarget_distance_weight = 1.0f;
10464     
10465             /* Skeleton Sketching */
10466             sce->toolsettings->bone_sketching = 0;
10467             sce->toolsettings->skgen_retarget_roll = SK_RETARGET_ROLL_VIEW;
10468         }
10469     }
10470     if (main->versionfile < 248 || (main->versionfile == 248 && main->subversionfile < 3)) {
10471         bScreen *sc;
10472         
10473         /* adjust default settings for Animation Editors */
10474         for (sc= main->screen.first; sc; sc= sc->id.next) {
10475             ScrArea *sa;
10476             
10477             for (sa= sc->areabase.first; sa; sa= sa->next) { 
10478                 SpaceLink *sl;
10479                 
10480                 for (sl= sa->spacedata.first; sl; sl= sl->next) {
10481                     switch (sl->spacetype) {
10482                         case SPACE_ACTION:
10483                         {
10484                             SpaceAction *sact= (SpaceAction *)sl;
10485                             
10486                             sact->mode= SACTCONT_DOPESHEET;
10487                             sact->autosnap= SACTSNAP_FRAME;
10488                         }
10489                             break;
10490                         case SPACE_IPO:
10491                         {
10492                             SpaceIpo *sipo= (SpaceIpo *)sl;
10493                             sipo->autosnap= SACTSNAP_FRAME;
10494                         }
10495                             break;
10496                         case SPACE_NLA:
10497                         {
10498                             SpaceNla *snla= (SpaceNla *)sl;
10499                             snla->autosnap= SACTSNAP_FRAME;
10500                         }
10501                             break;
10502                     }
10503                 }
10504             }
10505         }
10506     }
10507 
10508     if (main->versionfile < 248 || (main->versionfile == 248 && main->subversionfile < 3)) {
10509         Object *ob;
10510 
10511         /* Adjustments needed after Bullets update */
10512         for(ob = main->object.first; ob; ob= ob->id.next) {
10513             ob->damping *= 0.635f;
10514             ob->rdamping = 0.1f + (0.8f * ob->rdamping);
10515         }
10516     }
10517     
10518     if (main->versionfile < 248 || (main->versionfile == 248 && main->subversionfile < 4)) {
10519         Scene *sce;
10520         World *wrld;
10521 
10522         /*  Dome (Fisheye) default parameters  */
10523         for (sce= main->scene.first; sce; sce= sce->id.next) {
10524             sce->r.domeangle = 180;
10525             sce->r.domemode = 1;
10526             sce->r.domeres = 4;
10527             sce->r.domeresbuf = 1.0f;
10528             sce->r.dometilt = 0;
10529         }
10530         /* DBVT culling by default */
10531         for(wrld=main->world.first; wrld; wrld= wrld->id.next) {
10532             wrld->mode |= WO_DBVT_CULLING;
10533             wrld->occlusionRes = 128;
10534         }
10535     }
10536 
10537     if (main->versionfile < 248 || (main->versionfile == 248 && main->subversionfile < 5)) {
10538         Object *ob;
10539         World *wrld;
10540         for(ob = main->object.first; ob; ob= ob->id.next) {
10541             ob->m_contactProcessingThreshold = 1.; //pad3 is used for m_contactProcessingThreshold
10542             if(ob->parent) {
10543                 /* check if top parent has compound shape set and if yes, set this object
10544                    to compound shaper as well (was the behaviour before, now it's optional) */
10545                 Object *parent= newlibadr(fd, lib, ob->parent);
10546                 while (parent && parent != ob &&  parent->parent != NULL) {
10547                     parent = newlibadr(fd, lib, parent->parent);
10548                 }
10549                 if(parent) {
10550                     if (parent->gameflag & OB_CHILD)
10551                         ob->gameflag |= OB_CHILD;
10552                 }
10553             }
10554         }
10555         for(wrld=main->world.first; wrld; wrld= wrld->id.next) {
10556             wrld->ticrate = 60;
10557             wrld->maxlogicstep = 5;
10558             wrld->physubstep = 1;
10559             wrld->maxphystep = 5;
10560         }
10561     }
10562     
10563     // correct introduce of seed for wind force
10564     if (main->versionfile < 249 && main->subversionfile < 1) {
10565         Object *ob;
10566         for(ob = main->object.first; ob; ob= ob->id.next) {
10567             if(ob->pd)
10568                 ob->pd->seed = ((unsigned int)(ceil(PIL_check_seconds_timer()))+1) % 128;
10569         }
10570     
10571     }
10572 
10573     if (main->versionfile < 249 && main->subversionfile < 2) {
10574         Scene *sce= main->scene.first;
10575         Sequence *seq;
10576         Editing *ed;
10577         
10578         while(sce) {
10579             ed= sce->ed;
10580             if(ed) {
10581                 SEQP_BEGIN(ed, seq) {
10582                     if (seq->strip && seq->strip->proxy){
10583                         seq->strip->proxy->quality =90;
10584                     }
10585                 }
10586                 SEQ_END
10587             }
10588             
10589             sce= sce->id.next;
10590         }
10591 
10592     }
10593 
10594     if (main->versionfile < 250) {
10595         bScreen *screen;
10596         Scene *scene;
10597         Base *base;
10598         Material *ma;
10599         Camera *cam;
10600         Mesh *me;
10601         Curve *cu;
10602         Scene *sce;
10603         Tex *tx;
10604         ParticleSettings *part;
10605         Object *ob;
10606         //PTCacheID *pid;
10607         //ListBase pidlist;
10608 
10609         bSound *sound;
10610         Sequence *seq;
10611         bActuator *act;
10612         int a;
10613 
10614         for(sound = main->sound.first; sound; sound = sound->id.next)
10615         {
10616             if(sound->newpackedfile)
10617             {
10618                 sound->packedfile = sound->newpackedfile;
10619                 sound->newpackedfile = NULL;
10620             }
10621         }
10622 
10623         for(ob = main->object.first; ob; ob= ob->id.next) {
10624             for(act= ob->actuators.first; act; act= act->next) {
10625                 if (act->type == ACT_SOUND) {
10626                     bSoundActuator *sAct = (bSoundActuator*) act->data;
10627                     if(sAct->sound)
10628                     {
10629                         sound = newlibadr(fd, lib, sAct->sound);
10630                         sAct->flag = sound->flags & SOUND_FLAGS_3D ? ACT_SND_3D_SOUND : 0;
10631                         sAct->pitch = sound->pitch;
10632                         sAct->volume = sound->volume;
10633                         sAct->sound3D.reference_distance = sound->distance;
10634                         sAct->sound3D.max_gain = sound->max_gain;
10635                         sAct->sound3D.min_gain = sound->min_gain;
10636                         sAct->sound3D.rolloff_factor = sound->attenuation;
10637                     }
10638                     else
10639                     {
10640                         sAct->sound3D.reference_distance = 1.0f;
10641                         sAct->volume = 1.0f;
10642                         sAct->sound3D.max_gain = 1.0f;
10643                         sAct->sound3D.rolloff_factor = 1.0f;
10644                     }
10645                     sAct->sound3D.cone_inner_angle = 360.0f;
10646                     sAct->sound3D.cone_outer_angle = 360.0f;
10647                     sAct->sound3D.max_distance = FLT_MAX;
10648                 }
10649             }
10650         }
10651 
10652         for(scene = main->scene.first; scene; scene = scene->id.next)
10653         {
10654             if(scene->ed && scene->ed->seqbasep)
10655             {
10656                 SEQ_BEGIN(scene->ed, seq) {
10657                     if(seq->type == SEQ_HD_SOUND)
10658                     {
10659                         char str[FILE_MAX];
10660                         BLI_join_dirfile(str, sizeof(str), seq->strip->dir, seq->strip->stripdata->name);
10661                         BLI_path_abs(str, main->name);
10662                         seq->sound = sound_new_file(main, str);
10663                     }
10664                     /* don't know, if anybody used that
10665                        this way, but just in case, upgrade
10666                        to new way... */
10667                     if((seq->flag & SEQ_USE_PROXY_CUSTOM_FILE) &&
10668                        !(seq->flag & SEQ_USE_PROXY_CUSTOM_DIR))
10669                     {
10670                         
10671                         BLI_snprintf(seq->strip->proxy->dir, 
10672                              FILE_MAXDIR, "%s/BL_proxy", 
10673                              seq->strip->dir);
10674                     }
10675                 }
10676                 SEQ_END
10677             }
10678         }
10679 
10680         for(screen= main->screen.first; screen; screen= screen->id.next) {
10681             do_versions_windowmanager_2_50(screen);
10682             do_versions_gpencil_2_50(main, screen);
10683         }
10684         
10685         /* shader, composit and texture node trees have id.name empty, put something in
10686          * to have them show in RNA viewer and accessible otherwise.
10687          */
10688         for(ma= main->mat.first; ma; ma= ma->id.next) {
10689             if(ma->nodetree && ma->nodetree->id.name[0] == '\0')
10690                 strcpy(ma->nodetree->id.name, "NTShader Nodetree");
10691             
10692             /* which_output 0 is now "not specified" */
10693             for(a=0; a<MAX_MTEX; a++) {
10694                 if(ma->mtex[a]) {
10695                     tx= newlibadr(fd, lib, ma->mtex[a]->tex);
10696                     if(tx && tx->use_nodes)
10697                         ma->mtex[a]->which_output++;
10698                 }
10699             }
10700         }
10701         /* and composit trees */
10702         for(sce= main->scene.first; sce; sce= sce->id.next) {
10703             if(sce->nodetree && sce->nodetree->id.name[0] == '\0')
10704                 strcpy(sce->nodetree->id.name, "NTCompositing Nodetree");
10705 
10706             /* move to cameras */
10707             if(sce->r.mode & R_PANORAMA) {
10708                 for(base=sce->base.first; base; base=base->next) {
10709                     ob= newlibadr(fd, lib, base->object);
10710 
10711                     if(ob->type == OB_CAMERA && !ob->id.lib) {
10712                         cam= newlibadr(fd, lib, ob->data);
10713                         cam->flag |= CAM_PANORAMA;
10714                     }
10715                 }
10716 
10717                 sce->r.mode &= ~R_PANORAMA;
10718             }
10719         }
10720         /* and texture trees */
10721         for(tx= main->tex.first; tx; tx= tx->id.next) {
10722             bNode *node;
10723 
10724             if(tx->nodetree) {
10725                 if(tx->nodetree->id.name[0] == '\0')
10726                     strcpy(tx->nodetree->id.name, "NTTexture Nodetree");
10727 
10728                 /* which_output 0 is now "not specified" */
10729                 for(node=tx->nodetree->nodes.first; node; node=node->next)
10730                     if(node->type == TEX_NODE_OUTPUT)
10731                         node->custom1++;
10732             }
10733         }
10734         
10735         /* copy standard draw flag to meshes(used to be global, is not available here) */
10736         for(me= main->mesh.first; me; me= me->id.next) {
10737             me->drawflag= ME_DRAWEDGES|ME_DRAWFACES|ME_DRAWCREASES;
10738         }
10739 
10740         /* particle draw and render types */
10741         for(part= main->particle.first; part; part= part->id.next) {
10742             if(part->draw_as) {
10743                 if(part->draw_as == PART_DRAW_DOT) {
10744                     part->ren_as = PART_DRAW_HALO;
10745                     part->draw_as = PART_DRAW_REND;
10746                 }
10747                 else if(part->draw_as <= PART_DRAW_AXIS) {
10748                     part->ren_as = PART_DRAW_HALO;
10749                 }
10750                 else {
10751                     part->ren_as = part->draw_as;
10752                     part->draw_as = PART_DRAW_REND;
10753                 }
10754             }
10755             part->path_end = 1.0f;
10756             part->clength = 1.0f;
10757         }
10758         /* set old pointcaches to have disk cache flag */
10759         for(ob = main->object.first; ob; ob= ob->id.next) {
10760 
10761             //BKE_ptcache_ids_from_object(&pidlist, ob);
10762 
10763             //for(pid=pidlist.first; pid; pid=pid->next)
10764             //  pid->cache->flag |= PTCACHE_DISK_CACHE;
10765 
10766             //BLI_freelistN(&pidlist);
10767         }
10768 
10769         /* type was a mixed flag & enum. move the 2d flag elsewhere */
10770         for(cu = main->curve.first; cu; cu= cu->id.next) {
10771             Nurb *nu;
10772 
10773             for(nu= cu->nurb.first; nu; nu= nu->next) {
10774                 nu->flag |= (nu->type & CU_2D);
10775                 nu->type &= CU_TYPE;
10776             }
10777         }
10778     }
10779 
10780     if (main->versionfile < 250 || (main->versionfile == 250 && main->subversionfile < 1)) {
10781         Object *ob;
10782         Material *ma;
10783         Tex *tex;
10784         Scene *sce;
10785         ToolSettings *ts;
10786         //PTCacheID *pid;
10787         //ListBase pidlist;
10788 
10789         for(ob = main->object.first; ob; ob = ob->id.next) {
10790             //BKE_ptcache_ids_from_object(&pidlist, ob);
10791 
10792             //for(pid=pidlist.first; pid; pid=pid->next) {
10793             //  if(pid->ptcaches->first == NULL)
10794             //      pid->ptcaches->first = pid->ptcaches->last = pid->cache;
10795             //}
10796 
10797             //BLI_freelistN(&pidlist);
10798 
10799             if(ob->type == OB_MESH) {
10800                 Mesh *me = newlibadr(fd, lib, ob->data);
10801                 void *olddata = ob->data;
10802                 ob->data = me;
10803 
10804                 /* XXX - library meshes crash on loading most yoFrankie levels,
10805                  * the multires pointer gets invalid -  Campbell */
10806                 if(me && me->id.lib==NULL && me->mr && me->mr->level_count > 1) {
10807                     multires_load_old(ob, me);
10808                 }
10809 
10810                 ob->data = olddata;
10811             }
10812 
10813             if(ob->totcol && ob->matbits == NULL) {
10814                 int a;
10815 
10816                 ob->matbits= MEM_callocN(sizeof(char)*ob->totcol, "ob->matbits");
10817                 for(a=0; a<ob->totcol; a++)
10818                     ob->matbits[a]= ob->colbits & (1<<a);
10819             }
10820         }
10821 
10822         /* texture filter */
10823         for(tex = main->tex.first; tex; tex = tex->id.next) {
10824             if(tex->afmax == 0)
10825                 tex->afmax= 8;
10826         }
10827 
10828         for(ma = main->mat.first; ma; ma = ma->id.next) {
10829             int a;
10830             if(ma->mode & MA_WIRE) {
10831                 ma->material_type= MA_TYPE_WIRE;
10832                 ma->mode &= ~MA_WIRE;
10833             }
10834             if(ma->mode & MA_HALO) {
10835                 ma->material_type= MA_TYPE_HALO;
10836                 ma->mode &= ~MA_HALO;
10837             }
10838 
10839             if(ma->mode & (MA_ZTRANSP|MA_RAYTRANSP)) {
10840                 ma->mode |= MA_TRANSP;
10841             }
10842             else {
10843                 /* ma->mode |= MA_ZTRANSP; */ /* leave ztransp as is even if its not used [#28113] */
10844                 ma->mode &= ~MA_TRANSP;
10845             }
10846 
10847             /* set new bump for unused slots */
10848             for(a=0; a<MAX_MTEX; a++) {
10849                 if(ma->mtex[a]) {
10850                     tex= ma->mtex[a]->tex;
10851                     if(!tex) {
10852                         ma->mtex[a]->texflag |= MTEX_3TAP_BUMP;
10853                         ma->mtex[a]->texflag |= MTEX_BUMP_OBJECTSPACE;
10854                     } else {
10855                         tex= (Tex*)newlibadr(fd, ma->id.lib, tex);
10856                         if(tex && tex->type == 0) { /* invalid type */
10857                             ma->mtex[a]->texflag |= MTEX_3TAP_BUMP;
10858                             ma->mtex[a]->texflag |= MTEX_BUMP_OBJECTSPACE;
10859                         }
10860                     }
10861                 }
10862             }
10863             
10864             /* volume rendering settings */
10865             if (ma->vol.stepsize < 0.0001f) {
10866                 ma->vol.density = 1.0f;
10867                 ma->vol.emission = 0.0f;
10868                 ma->vol.scattering = 1.0f;
10869                 ma->vol.emission_col[0] = ma->vol.emission_col[1] = ma->vol.emission_col[2] = 1.0f;
10870                 ma->vol.density_scale = 1.0f;
10871                 ma->vol.depth_cutoff = 0.01f;
10872                 ma->vol.stepsize_type = MA_VOL_STEP_RANDOMIZED;
10873                 ma->vol.stepsize = 0.2f;
10874                 ma->vol.shade_type = MA_VOL_SHADE_SHADED;
10875                 ma->vol.shadeflag |= MA_VOL_PRECACHESHADING;
10876                 ma->vol.precache_resolution = 50;
10877             }
10878         }
10879 
10880         for(sce = main->scene.first; sce; sce = sce->id.next) {
10881             ts= sce->toolsettings;
10882             if(ts->normalsize == 0.0f || !ts->uv_selectmode || ts->vgroup_weight == 0.0f) {
10883                 ts->normalsize= 0.1f;
10884                 ts->selectmode= SCE_SELECT_VERTEX;
10885                 
10886                 /* autokeying - setting should be taken from the user-prefs
10887                  * but the userprefs version may not have correct flags set 
10888                  * (i.e. will result in blank box when enabled)
10889                  */
10890                 ts->autokey_mode= U.autokey_mode;
10891                 if (ts->autokey_mode == 0) 
10892                     ts->autokey_mode= 2; /* 'add/replace' but not on */
10893                 ts->uv_selectmode= UV_SELECT_VERTEX;
10894                 ts->vgroup_weight= 1.0f;
10895             }
10896 
10897             /* Game Settings */
10898             //Dome
10899             sce->gm.dome.angle = sce->r.domeangle;
10900             sce->gm.dome.mode = sce->r.domemode;
10901             sce->gm.dome.res = sce->r.domeres;
10902             sce->gm.dome.resbuf = sce->r.domeresbuf;
10903             sce->gm.dome.tilt = sce->r.dometilt;
10904             sce->gm.dome.warptext = sce->r.dometext;
10905 
10906             //Stand Alone
10907             sce->gm.playerflag |= (sce->r.fullscreen?GAME_PLAYER_FULLSCREEN:0);
10908             sce->gm.xplay = sce->r.xplay;
10909             sce->gm.yplay = sce->r.yplay;
10910             sce->gm.freqplay = sce->r.freqplay;
10911             sce->gm.depth = sce->r.depth;
10912             sce->gm.attrib = sce->r.attrib;
10913 
10914             //Stereo
10915             sce->gm.stereomode = sce->r.stereomode;
10916             /* reassigning stereomode NO_STEREO and DOME to a separeted flag*/
10917             if (sce->gm.stereomode == 1){ //1 = STEREO_NOSTEREO
10918                 sce->gm.stereoflag = STEREO_NOSTEREO;
10919                 sce->gm.stereomode = STEREO_ANAGLYPH;
10920             }
10921             else if(sce->gm.stereomode == 8){ //8 = STEREO_DOME
10922                 sce->gm.stereoflag = STEREO_DOME;
10923                 sce->gm.stereomode = STEREO_ANAGLYPH;
10924             }
10925             else
10926                 sce->gm.stereoflag = STEREO_ENABLED;
10927 
10928             //Framing
10929             sce->gm.framing = sce->framing;
10930             sce->gm.xplay = sce->r.xplay;
10931             sce->gm.yplay = sce->r.yplay;
10932             sce->gm.freqplay= sce->r.freqplay;
10933             sce->gm.depth= sce->r.depth;
10934 
10935             //Physic (previously stored in world)
10936             sce->gm.gravity =9.8f;
10937             sce->gm.physicsEngine= WOPHY_BULLET;// Bullet by default
10938             sce->gm.mode = WO_DBVT_CULLING; // DBVT culling by default
10939             sce->gm.occlusionRes = 128;
10940             sce->gm.ticrate = 60;
10941             sce->gm.maxlogicstep = 5;
10942             sce->gm.physubstep = 1;
10943             sce->gm.maxphystep = 5;
10944         }
10945     }
10946 
10947     if (main->versionfile < 250 || (main->versionfile == 250 && main->subversionfile < 2)) {
10948         Scene *sce;
10949         Object *ob;
10950 
10951         for(sce = main->scene.first; sce; sce = sce->id.next) {
10952             if(fd->fileflags & G_FILE_ENABLE_ALL_FRAMES)
10953                 sce->gm.flag |= GAME_ENABLE_ALL_FRAMES;
10954             if(fd->fileflags & G_FILE_SHOW_DEBUG_PROPS)
10955                 sce->gm.flag |= GAME_SHOW_DEBUG_PROPS;
10956             if(fd->fileflags & G_FILE_SHOW_FRAMERATE)
10957                 sce->gm.flag |= GAME_SHOW_FRAMERATE;
10958             if(fd->fileflags & G_FILE_SHOW_PHYSICS)
10959                 sce->gm.flag |= GAME_SHOW_PHYSICS;
10960             if(fd->fileflags & G_FILE_GLSL_NO_SHADOWS)
10961                 sce->gm.flag |= GAME_GLSL_NO_SHADOWS;
10962             if(fd->fileflags & G_FILE_GLSL_NO_SHADERS)
10963                 sce->gm.flag |= GAME_GLSL_NO_SHADERS;
10964             if(fd->fileflags & G_FILE_GLSL_NO_RAMPS)
10965                 sce->gm.flag |= GAME_GLSL_NO_RAMPS;
10966             if(fd->fileflags & G_FILE_GLSL_NO_NODES)
10967                 sce->gm.flag |= GAME_GLSL_NO_NODES;
10968             if(fd->fileflags & G_FILE_GLSL_NO_EXTRA_TEX)
10969                 sce->gm.flag |= GAME_GLSL_NO_EXTRA_TEX;
10970             if(fd->fileflags & G_FILE_IGNORE_DEPRECATION_WARNINGS)
10971                 sce->gm.flag |= GAME_IGNORE_DEPRECATION_WARNINGS;
10972 
10973             if(fd->fileflags & G_FILE_GAME_MAT_GLSL)
10974                 sce->gm.matmode= GAME_MAT_GLSL;
10975             else if(fd->fileflags & G_FILE_GAME_MAT)
10976                 sce->gm.matmode= GAME_MAT_MULTITEX;
10977             else
10978                 sce->gm.matmode= GAME_MAT_TEXFACE;
10979 
10980             sce->gm.flag |= GAME_DISPLAY_LISTS;
10981         }
10982         
10983         for(ob = main->object.first; ob; ob = ob->id.next) {
10984             if(ob->flag & 8192) // OB_POSEMODE = 8192
10985                 ob->mode |= OB_MODE_POSE;
10986         }
10987     }
10988 
10989     if (main->versionfile < 250 || (main->versionfile == 250 && main->subversionfile < 4)) {
10990         Scene *sce;
10991         Object *ob;
10992         Material *ma;
10993         Lamp *la;
10994         World *wo;
10995         Tex *tex;
10996         ParticleSettings *part;
10997         int do_gravity = 0;
10998 
10999         for(sce = main->scene.first; sce; sce = sce->id.next)
11000             if(sce->unit.scale_length == 0.0f)
11001                 sce->unit.scale_length= 1.0f;
11002         
11003         for(ob = main->object.first; ob; ob = ob->id.next) {
11004             /* fluid-sim stuff */
11005             FluidsimModifierData *fluidmd = (FluidsimModifierData *)modifiers_findByType(ob, eModifierType_Fluidsim);
11006             if (fluidmd) fluidmd->fss->fmd = fluidmd;
11007             
11008             /* rotation modes were added, but old objects would now default to being 'quaternion based' */
11009             ob->rotmode= ROT_MODE_EUL;
11010         }
11011         
11012         for(ma = main->mat.first; ma; ma=ma->id.next) {
11013             if(ma->vol.reflection == 0.f) {
11014                 ma->vol.reflection = 1.f;
11015                 ma->vol.transmission_col[0] = ma->vol.transmission_col[1] = ma->vol.transmission_col[2] = 1.0f;
11016                 ma->vol.reflection_col[0] = ma->vol.reflection_col[1] = ma->vol.reflection_col[2] = 1.0f;
11017             }
11018 
11019             do_version_mtex_factor_2_50(ma->mtex, ID_MA);
11020         }
11021 
11022         for(la = main->lamp.first; la; la=la->id.next)
11023             do_version_mtex_factor_2_50(la->mtex, ID_LA);
11024 
11025         for(wo = main->world.first; wo; wo=wo->id.next)
11026             do_version_mtex_factor_2_50(wo->mtex, ID_WO);
11027 
11028         for(tex = main->tex.first; tex; tex=tex->id.next)
11029             if(tex->vd)
11030                 if(tex->vd->extend == 0)
11031                     tex->vd->extend = TEX_CLIP;
11032         
11033         for(sce= main->scene.first; sce; sce= sce->id.next)
11034         {
11035             if(sce->audio.main == 0.0f)
11036                 sce->audio.main = 1.0f;
11037 
11038             sce->r.ffcodecdata.audio_mixrate = sce->audio.mixrate;
11039             sce->r.ffcodecdata.audio_volume = sce->audio.main;
11040             sce->audio.distance_model = 2;
11041             sce->audio.doppler_factor = 1.0f;
11042             sce->audio.speed_of_sound = 343.3f;
11043         }
11044 
11045         /* Add default gravity to scenes */
11046         for(sce= main->scene.first; sce; sce= sce->id.next) {
11047             if((sce->physics_settings.flag & PHYS_GLOBAL_GRAVITY) == 0
11048                 && len_v3(sce->physics_settings.gravity) == 0.0f) {
11049 
11050                 sce->physics_settings.gravity[0] = sce->physics_settings.gravity[1] = 0.0f;
11051                 sce->physics_settings.gravity[2] = -9.81f;
11052                 sce->physics_settings.flag = PHYS_GLOBAL_GRAVITY;
11053                 do_gravity = 1;
11054             }
11055         }
11056 
11057         /* Assign proper global gravity weights for dynamics (only z-coordinate is taken into account) */
11058         if(do_gravity) for(part= main->particle.first; part; part= part->id.next)
11059             part->effector_weights->global_gravity = part->acc[2]/-9.81f;
11060 
11061         for(ob = main->object.first; ob; ob = ob->id.next) {
11062             ModifierData *md;
11063 
11064             if(do_gravity) {
11065                 for(md= ob->modifiers.first; md; md= md->next) {
11066                     ClothModifierData *clmd = (ClothModifierData *)modifiers_findByType(ob, eModifierType_Cloth);
11067                     if(clmd)
11068                         clmd->sim_parms->effector_weights->global_gravity = clmd->sim_parms->gravity[2]/-9.81f;
11069                 }
11070 
11071                 if(ob->soft)
11072                     ob->soft->effector_weights->global_gravity = ob->soft->grav/9.81f;
11073             }
11074 
11075             /* Normal wind shape is plane */
11076             if(ob->pd) {
11077                 if(ob->pd->forcefield == PFIELD_WIND)
11078                     ob->pd->shape = PFIELD_SHAPE_PLANE;
11079                 
11080                 if(ob->pd->flag & PFIELD_PLANAR)
11081                     ob->pd->shape = PFIELD_SHAPE_PLANE;
11082                 else if(ob->pd->flag & PFIELD_SURFACE)
11083                     ob->pd->shape = PFIELD_SHAPE_SURFACE;
11084 
11085                 ob->pd->flag |= PFIELD_DO_LOCATION;
11086             }
11087         }
11088     }
11089 
11090     if (main->versionfile < 250 || (main->versionfile == 250 && main->subversionfile < 6)) {
11091         Object *ob;
11092         Lamp *la;
11093         
11094         /* New variables for axis-angle rotations and/or quaternion rotations were added, and need proper initialisation */
11095         for (ob= main->object.first; ob; ob= ob->id.next) {
11096             /* new variables for all objects */
11097             ob->quat[0]= 1.0f;
11098             ob->rotAxis[1]= 1.0f;
11099             
11100             /* bones */
11101             if (ob->pose) {
11102                 bPoseChannel *pchan;
11103                 
11104                 for (pchan= ob->pose->chanbase.first; pchan; pchan= pchan->next) {
11105                     /* just need to initalise rotation axis properly... */
11106                     pchan->rotAxis[1]= 1.0f;
11107                 }
11108             }
11109         }
11110 
11111         for(la = main->lamp.first; la; la=la->id.next)
11112             la->compressthresh= 0.05f;
11113     }
11114 
11115     if (main->versionfile < 250 || (main->versionfile == 250 && main->subversionfile < 7)) {
11116         Mesh *me;
11117         Nurb *nu;
11118         Lattice *lt;
11119         Curve *cu;
11120         Key *key;
11121         float *data;
11122         int a, tot;
11123 
11124         /* shape keys are no longer applied to the mesh itself, but rather
11125            to the derivedmesh/displist, so here we ensure that the basis
11126            shape key is always set in the mesh coordinates. */
11127 
11128         for(me= main->mesh.first; me; me= me->id.next) {
11129             if((key = newlibadr(fd, lib, me->key)) && key->refkey) {
11130                 data= key->refkey->data;
11131                 tot= MIN2(me->totvert, key->refkey->totelem);
11132 
11133                 for(a=0; a<tot; a++, data+=3)
11134                     copy_v3_v3(me->mvert[a].co, data);
11135             }
11136         }
11137 
11138         for(lt= main->latt.first; lt; lt= lt->id.next) {
11139             if((key = newlibadr(fd, lib, lt->key)) && key->refkey) {
11140                 data= key->refkey->data;
11141                 tot= MIN2(lt->pntsu*lt->pntsv*lt->pntsw, key->refkey->totelem);
11142 
11143                 for(a=0; a<tot; a++, data+=3)
11144                     copy_v3_v3(lt->def[a].vec, data);
11145             }
11146         }
11147 
11148         for(cu= main->curve.first; cu; cu= cu->id.next) {
11149             if((key = newlibadr(fd, lib, cu->key)) && key->refkey) {
11150                 data= key->refkey->data;
11151 
11152                 for(nu=cu->nurb.first; nu; nu=nu->next) {
11153                     if(nu->bezt) {
11154                         BezTriple *bezt = nu->bezt;
11155 
11156                         for(a=0; a<nu->pntsu; a++, bezt++) {
11157                             copy_v3_v3(bezt->vec[0], data); data+=3;
11158                             copy_v3_v3(bezt->vec[1], data); data+=3;
11159                             copy_v3_v3(bezt->vec[2], data); data+=3;
11160                             bezt->alfa= *data; data++;
11161                         }
11162                     }
11163                     else if(nu->bp) {
11164                         BPoint *bp = nu->bp;
11165 
11166                         for(a=0; a<nu->pntsu*nu->pntsv; a++, bp++) {
11167                             copy_v3_v3(bp->vec, data); data+=3;
11168                             bp->alfa= *data; data++;
11169                         }
11170                     }
11171                 }
11172             }
11173         }
11174     }
11175 
11176     if (main->versionfile < 250 || (main->versionfile == 250 && main->subversionfile < 8))
11177     {
11178         {
11179             Scene *sce= main->scene.first;
11180             while(sce) {
11181                 if(sce->r.frame_step==0)
11182                     sce->r.frame_step= 1;
11183                 if (sce->r.mblur_samples==0)
11184                     sce->r.mblur_samples = sce->r.osa;
11185                 
11186                 if (sce->ed && sce->ed->seqbase.first) {
11187                     do_versions_seq_unique_name_all_strips(
11188                         sce, &sce->ed->seqbase);
11189                 }
11190             
11191                 sce= sce->id.next;
11192             }
11193         }
11194         {
11195             /* ensure all nodes have unique names */
11196             bNodeTree *ntree= main->nodetree.first;
11197             while(ntree) {
11198                 bNode *node=ntree->nodes.first;
11199                 
11200                 while(node) {
11201                     nodeUniqueName(ntree, node);
11202                     node= node->next;
11203                 }
11204                 
11205                 ntree= ntree->id.next;
11206             }
11207         }
11208         {
11209             Object *ob=main->object.first;
11210             while (ob) {
11211                 /* shaded mode disabled for now */
11212                 if (ob->dt == OB_MATERIAL) ob->dt = OB_TEXTURE;
11213                 ob=ob->id.next;
11214             }
11215         }
11216         
11217         {
11218             bScreen *screen;
11219             ScrArea *sa;
11220             SpaceLink *sl;
11221             
11222             for(screen= main->screen.first; screen; screen= screen->id.next) {
11223                 for(sa= screen->areabase.first; sa; sa= sa->next) {
11224                     for(sl= sa->spacedata.first; sl; sl= sl->next) {
11225                         if(sl->spacetype==SPACE_VIEW3D) {
11226                             View3D *v3d = (View3D *)sl;
11227                             if (v3d->drawtype == OB_MATERIAL) v3d->drawtype = OB_SOLID;
11228                         }
11229                     }
11230                 }
11231             }
11232         }
11233         
11234         /* only convert old 2.50 files with color management */
11235         if (main->versionfile == 250) {
11236             Scene *sce=main->scene.first;
11237             Material *ma=main->mat.first;
11238             World *wo=main->world.first;
11239             Tex *tex=main->tex.first;
11240             int i, convert=0;
11241             
11242             /* convert to new color management system:
11243              while previously colors were stored as srgb, 
11244              now they are stored as linear internally, 
11245              with screen gamma correction in certain places in the UI. */
11246 
11247             /* don't know what scene is active, so we'll convert if any scene has it enabled... */
11248             while (sce) {
11249                 if(sce->r.color_mgt_flag & R_COLOR_MANAGEMENT)
11250                     convert=1;
11251                 sce=sce->id.next;
11252             }
11253             
11254             if (convert) {
11255                 while(ma) {
11256                     if (ma->ramp_col) {
11257                         ColorBand *band = (ColorBand *)ma->ramp_col;
11258                         for (i=0; i<band->tot; i++) {
11259                             CBData *data = band->data + i;
11260                             srgb_to_linearrgb_v3_v3(&data->r, &data->r);
11261                         }
11262                     }
11263                     if (ma->ramp_spec) {
11264                         ColorBand *band = (ColorBand *)ma->ramp_spec;
11265                         for (i=0; i<band->tot; i++) {
11266                             CBData *data = band->data + i;
11267                             srgb_to_linearrgb_v3_v3(&data->r, &data->r);
11268                         }
11269                     }
11270                     
11271                     srgb_to_linearrgb_v3_v3(&ma->r, &ma->r);
11272                     srgb_to_linearrgb_v3_v3(&ma->specr, &ma->specr);
11273                     srgb_to_linearrgb_v3_v3(&ma->mirr, &ma->mirr);
11274                     srgb_to_linearrgb_v3_v3(ma->sss_col, ma->sss_col);
11275                     ma=ma->id.next;
11276                 }
11277                 
11278                 while(tex) {
11279                     if (tex->coba) {
11280                         ColorBand *band = (ColorBand *)tex->coba;
11281                         for (i=0; i<band->tot; i++) {
11282                             CBData *data = band->data + i;
11283                             srgb_to_linearrgb_v3_v3(&data->r, &data->r);
11284                         }
11285                     }
11286                     tex=tex->id.next;
11287                 }
11288                 
11289                 while(wo) {
11290                     srgb_to_linearrgb_v3_v3(&wo->ambr, &wo->ambr);
11291                     srgb_to_linearrgb_v3_v3(&wo->horr, &wo->horr);
11292                     srgb_to_linearrgb_v3_v3(&wo->zenr, &wo->zenr);
11293                     wo=wo->id.next;
11294                 }
11295             }
11296         }
11297     }
11298     
11299     if (main->versionfile < 250 || (main->versionfile == 250 && main->subversionfile < 9))
11300     {
11301         Scene *sce;
11302         Mesh *me;
11303         Object *ob;
11304 
11305         for(sce=main->scene.first; sce; sce=sce->id.next)
11306             if(!sce->toolsettings->particle.selectmode)
11307                 sce->toolsettings->particle.selectmode= SCE_SELECT_PATH;
11308 
11309         if (main->versionfile == 250 && main->subversionfile > 1) {
11310             for(me=main->mesh.first; me; me=me->id.next)
11311                 multires_load_old_250(me);
11312 
11313             for(ob=main->object.first; ob; ob=ob->id.next) {
11314                 MultiresModifierData *mmd = (MultiresModifierData *)modifiers_findByType(ob, eModifierType_Multires);
11315 
11316                 if(mmd) {
11317                     mmd->totlvl--;
11318                     mmd->lvl--;
11319                     mmd->sculptlvl= mmd->lvl;
11320                     mmd->renderlvl= mmd->lvl;
11321                 }
11322             }
11323         }
11324     }
11325 
11326     if (main->versionfile < 250 || (main->versionfile == 250 && main->subversionfile < 10))
11327     {
11328         Object *ob;
11329 
11330         /* properly initialise hair clothsim data on old files */
11331         for(ob = main->object.first; ob; ob = ob->id.next) {
11332             ModifierData *md;
11333             for(md= ob->modifiers.first; md; md= md->next) {
11334                 if (md->type == eModifierType_Cloth) {
11335                     ClothModifierData *clmd = (ClothModifierData *)md;
11336                     if (clmd->sim_parms->velocity_smooth < 0.01f)
11337                         clmd->sim_parms->velocity_smooth = 0.f;
11338                 }
11339             }
11340         }
11341     }
11342 
11343     /* fix bad area setup in subversion 10 */
11344     if (main->versionfile == 250 && main->subversionfile == 10)
11345     {
11346         /* fix for new view type in sequencer */
11347         bScreen *screen;
11348         ScrArea *sa;
11349         SpaceLink *sl;
11350 
11351 
11352         /* remove all preview window in wrong spaces */
11353         for(screen= main->screen.first; screen; screen= screen->id.next) {
11354             for(sa= screen->areabase.first; sa; sa= sa->next) {
11355                 for(sl= sa->spacedata.first; sl; sl= sl->next) {
11356                     if(sl->spacetype!=SPACE_SEQ) {
11357                         ARegion *ar;
11358                         ListBase *regionbase;
11359 
11360                         if (sl == sa->spacedata.first) {
11361                             regionbase = &sa->regionbase;
11362                         } else {
11363                             regionbase = &sl->regionbase;
11364                         }
11365 
11366 
11367                         for( ar = regionbase->first; ar; ar = ar->next) {
11368                             if (ar->regiontype == RGN_TYPE_PREVIEW)
11369                                 break;
11370                         }
11371 
11372                         if (ar && (ar->regiontype == RGN_TYPE_PREVIEW)) {
11373                             SpaceType *st= BKE_spacetype_from_id(SPACE_SEQ);
11374                             BKE_area_region_free(st, ar);
11375                             BLI_freelinkN(regionbase, ar);
11376                         }
11377                     }
11378                 }
11379             }
11380         }
11381     }
11382 
11383     if (main->versionfile < 250 || (main->versionfile == 250 && main->subversionfile < 11))
11384     {
11385         {
11386             /* fix for new view type in sequencer */
11387             bScreen *screen;
11388             ScrArea *sa;
11389             SpaceLink *sl;
11390 
11391 
11392             for(screen= main->screen.first; screen; screen= screen->id.next) {
11393                 for(sa= screen->areabase.first; sa; sa= sa->next) {
11394                     for(sl= sa->spacedata.first; sl; sl= sl->next) {
11395                         if(sl->spacetype==SPACE_SEQ) {
11396                             ARegion *ar;
11397                             ARegion *ar_main;
11398                             ListBase *regionbase;
11399                             SpaceSeq *sseq = (SpaceSeq *)sl;
11400 
11401                             if (sl == sa->spacedata.first) {
11402                                 regionbase = &sa->regionbase;
11403                             } else {
11404                                 regionbase = &sl->regionbase;
11405                             }
11406 
11407                             if (sseq->view == 0) sseq->view = SEQ_VIEW_SEQUENCE;
11408                             if (sseq->mainb == 0) sseq->mainb = SEQ_DRAW_IMG_IMBUF;
11409 
11410                             ar_main = (ARegion*)regionbase->first;
11411                             for (; ar_main; ar_main = ar_main->next) {
11412                                 if (ar_main->regiontype == RGN_TYPE_WINDOW)
11413                                     break;
11414                             }
11415                             ar= MEM_callocN(sizeof(ARegion), "preview area for sequencer");
11416                             BLI_insertlinkbefore(regionbase, ar_main, ar);
11417                             sequencer_init_preview_region(ar);
11418                         }
11419                     }
11420                 }
11421             }
11422         }
11423     }
11424 
11425     if (main->versionfile < 250 || (main->versionfile == 250 && main->subversionfile < 12))
11426     {
11427         Scene *sce;
11428         Object *ob;
11429         Brush *brush;
11430         Material *ma;
11431         
11432         /* game engine changes */
11433         for(sce = main->scene.first; sce; sce = sce->id.next) {
11434             sce->gm.eyeseparation = 0.10f;
11435         }
11436         
11437         /* anim viz changes */
11438         for (ob= main->object.first; ob; ob= ob->id.next) {
11439             /* initialise object defaults */
11440             animviz_settings_init(&ob->avs);
11441             
11442             /* if armature, copy settings for pose from armature data 
11443              * performing initialisation where appropriate 
11444              */
11445             if (ob->pose && ob->data) {
11446                 bArmature *arm= newlibadr(fd, lib, ob->data);
11447                 if(arm) { /* XXX - why does this fail in some cases? */
11448                     bAnimVizSettings *avs= &ob->pose->avs;
11449                     
11450                     /* ghosting settings ---------------- */
11451                         /* ranges */
11452                     avs->ghost_bc= avs->ghost_ac= arm->ghostep;
11453                     
11454                     avs->ghost_sf= arm->ghostsf;
11455                     avs->ghost_ef= arm->ghostef;
11456                     if ((avs->ghost_sf == avs->ghost_ef) && (avs->ghost_sf == 0)) {
11457                         avs->ghost_sf= 1;
11458                         avs->ghost_ef= 100;
11459                     }
11460                     
11461                         /* type */
11462                     if (arm->ghostep == 0)
11463                         avs->ghost_type= GHOST_TYPE_NONE;
11464                     else
11465                         avs->ghost_type= arm->ghosttype + 1;
11466                     
11467                         /* stepsize */
11468                     avs->ghost_step= arm->ghostsize;
11469                     if (avs->ghost_step == 0)
11470                         avs->ghost_step= 1;
11471                     
11472                     /* path settings --------------------- */
11473                         /* ranges */
11474                     avs->path_bc= arm->pathbc;
11475                     avs->path_ac= arm->pathac;
11476                     if ((avs->path_bc == avs->path_ac) && (avs->path_bc == 0))
11477                         avs->path_bc= avs->path_ac= 10;
11478                     
11479                     avs->path_sf= arm->pathsf;
11480                     avs->path_ef= arm->pathef;
11481                     if ((avs->path_sf == avs->path_ef) && (avs->path_sf == 0)) {
11482                         avs->path_sf= 1;
11483                         avs->path_ef= 250;
11484                     }
11485                     
11486                         /* flags */
11487                     if (arm->pathflag & ARM_PATH_FNUMS)
11488                         avs->path_viewflag |= MOTIONPATH_VIEW_FNUMS;
11489                     if (arm->pathflag & ARM_PATH_KFRAS)
11490                         avs->path_viewflag |= MOTIONPATH_VIEW_KFRAS;
11491                     if (arm->pathflag & ARM_PATH_KFNOS)
11492                         avs->path_viewflag |= MOTIONPATH_VIEW_KFNOS;
11493                     
11494                         /* bake flags */
11495                     if (arm->pathflag & ARM_PATH_HEADS)
11496                         avs->path_bakeflag |= MOTIONPATH_BAKE_HEADS;
11497                     
11498                         /* type */
11499                     if (arm->pathflag & ARM_PATH_ACFRA)
11500                         avs->path_type = MOTIONPATH_TYPE_ACFRA;
11501                     
11502                         /* stepsize */
11503                     avs->path_step= arm->pathsize;
11504                     if (avs->path_step == 0)
11505                         avs->path_step= 1;
11506                 }
11507                 else
11508                     animviz_settings_init(&ob->pose->avs);
11509             }
11510         }
11511         
11512         /* brush texture changes */
11513         for (brush= main->brush.first; brush; brush= brush->id.next) {
11514             default_mtex(&brush->mtex);
11515         }
11516 
11517         for (ma= main->mat.first; ma; ma= ma->id.next) {
11518             if (ma->vol.ms_spread < 0.0001f) {
11519                 ma->vol.ms_spread = 0.2f;
11520                 ma->vol.ms_diff = 1.f;
11521                 ma->vol.ms_intensity = 1.f; 
11522             }
11523         }
11524     }
11525     
11526     if (main->versionfile < 250 || (main->versionfile == 250 && main->subversionfile < 13)) {
11527         /* NOTE: if you do more conversion, be sure to do it outside of this and
11528            increase subversion again, otherwise it will not be correct */
11529         Object *ob;
11530         
11531         /* convert degrees to radians for internal use */
11532         for (ob=main->object.first; ob; ob=ob->id.next) {
11533             bPoseChannel *pchan;
11534 
11535             do_version_constraints_radians_degrees_250(&ob->constraints);
11536 
11537             if (ob->pose) {
11538                 for (pchan=ob->pose->chanbase.first; pchan; pchan=pchan->next) {
11539                     pchan->limitmin[0] *= (float)(M_PI/180.0);
11540                     pchan->limitmin[1] *= (float)(M_PI/180.0);
11541                     pchan->limitmin[2] *= (float)(M_PI/180.0);
11542                     pchan->limitmax[0] *= (float)(M_PI/180.0);
11543                     pchan->limitmax[1] *= (float)(M_PI/180.0);
11544                     pchan->limitmax[2] *= (float)(M_PI/180.0);
11545 
11546                     do_version_constraints_radians_degrees_250(&pchan->constraints);
11547                 }
11548             }
11549         }
11550     }
11551     
11552     if (main->versionfile < 250 || (main->versionfile == 250 && main->subversionfile < 14)) {
11553         /* fix for bad View2D extents for Animation Editors */
11554         bScreen *screen;
11555         ScrArea *sa;
11556         SpaceLink *sl;
11557         
11558         for (screen= main->screen.first; screen; screen= screen->id.next) {
11559             for (sa= screen->areabase.first; sa; sa= sa->next) {
11560                 for (sl= sa->spacedata.first; sl; sl= sl->next) {
11561                     ListBase *regionbase;
11562                     ARegion *ar;
11563                     
11564                     if (sl == sa->spacedata.first)
11565                         regionbase = &sa->regionbase;
11566                     else
11567                         regionbase = &sl->regionbase;
11568                         
11569                     if (ELEM(sl->spacetype, SPACE_ACTION, SPACE_NLA)) {
11570                         for (ar = (ARegion*)regionbase->first; ar; ar = ar->next) {
11571                             if (ar->regiontype == RGN_TYPE_WINDOW) {
11572                                 ar->v2d.cur.ymax= ar->v2d.tot.ymax= 0.0f;
11573                                 ar->v2d.cur.ymin= ar->v2d.tot.ymin= (float)(-sa->winy) / 3.0f;
11574                             }
11575                         }
11576                     }
11577                 }
11578             }
11579         }
11580     }
11581     
11582     if (main->versionfile < 250 || (main->versionfile == 250 && main->subversionfile < 15)) {
11583         World *wo;
11584         Material *ma;
11585 
11586         /* ambient default from 0.5f to 1.0f */
11587         for(ma= main->mat.first; ma; ma=ma->id.next)
11588             ma->amb *= 2.0f;
11589 
11590         for(wo= main->world.first; wo; wo=wo->id.next) {
11591             /* ao splitting into ao/env/indirect */
11592             wo->ao_env_energy= wo->aoenergy;
11593             wo->aoenergy= 1.0f;
11594 
11595             if(wo->ao_indirect_bounces == 0)
11596                 wo->ao_indirect_bounces= 1;
11597             else
11598                 wo->mode |= WO_INDIRECT_LIGHT;
11599 
11600             if(wo->aomix == WO_AOSUB)
11601                 wo->ao_env_energy= -wo->ao_env_energy;
11602             else if(wo->aomix == WO_AOADDSUB)
11603                 wo->mode |= WO_AMB_OCC;
11604 
11605             wo->aomix= WO_AOMUL;
11606 
11607             /* ambient default from 0.5f to 1.0f */
11608             mul_v3_fl(&wo->ambr, 0.5f);
11609             wo->ao_env_energy *= 0.5f;
11610         }
11611     }
11612     
11613     if (main->versionfile < 250 || (main->versionfile == 250 && main->subversionfile < 17)) {
11614         Scene *sce;
11615         Sequence *seq;
11616         Material *ma;
11617 
11618         /* initialize to sane default so toggling on border shows something */
11619         for(sce = main->scene.first; sce; sce = sce->id.next) {
11620             if(sce->r.border.xmin == 0.0f && sce->r.border.ymin == 0.0f &&
11621                sce->r.border.xmax == 0.0f && sce->r.border.ymax == 0.0f) {
11622                 sce->r.border.xmin= 0.0f;
11623                 sce->r.border.ymin= 0.0f;
11624                 sce->r.border.xmax= 1.0f;
11625                 sce->r.border.ymax= 1.0f;
11626             }
11627 
11628             if((sce->r.ffcodecdata.flags & FFMPEG_MULTIPLEX_AUDIO) == 0)
11629                 sce->r.ffcodecdata.audio_codec = 0x0; // CODEC_ID_NONE
11630 
11631             SEQ_BEGIN(sce->ed, seq) {
11632                 seq->volume = 1.0f;
11633             }
11634             SEQ_END
11635         }
11636 
11637         /* particle brush strength factor was changed from int to float */
11638         for(sce= main->scene.first; sce; sce=sce->id.next) {
11639             ParticleEditSettings *pset= &sce->toolsettings->particle;
11640             int a;
11641 
11642             for(a=0; a<PE_TOT_BRUSH; a++)
11643                 pset->brush[a].strength /= 100.0f;
11644         }
11645 
11646         for(ma = main->mat.first; ma; ma=ma->id.next)
11647             if(ma->mode & MA_TRACEBLE)
11648                 ma->shade_flag |= MA_APPROX_OCCLUSION;
11649 
11650         /* sequencer changes */
11651         {
11652             bScreen *screen;
11653             ScrArea *sa;
11654             SpaceLink *sl;
11655 
11656             for(screen= main->screen.first; screen; screen= screen->id.next) {
11657                 for(sa= screen->areabase.first; sa; sa= sa->next) {
11658                     for(sl= sa->spacedata.first; sl; sl= sl->next) {
11659                         if(sl->spacetype==SPACE_SEQ) {
11660                             ARegion *ar_preview;
11661                             ListBase *regionbase;
11662 
11663                             if (sl == sa->spacedata.first) {
11664                                 regionbase = &sa->regionbase;
11665                             } else {
11666                                 regionbase = &sl->regionbase;
11667                             }
11668 
11669                             ar_preview = (ARegion*)regionbase->first;
11670                             for (; ar_preview; ar_preview = ar_preview->next) {
11671                                 if (ar_preview->regiontype == RGN_TYPE_PREVIEW)
11672                                     break;
11673                             }
11674                             if (ar_preview && (ar_preview->regiontype == RGN_TYPE_PREVIEW)) {
11675                                 sequencer_init_preview_region(ar_preview);
11676                             }
11677                         }
11678                     }
11679                 }
11680             }
11681         } /* sequencer changes */
11682     }
11683     
11684     if (main->versionfile <= 251) { /* 2.5.1 had no subversions */
11685         bScreen *sc;
11686         
11687         /* Blender 2.5.2 - subversion 0 introduced a new setting: V3D_RENDER_OVERRIDE.
11688          * This bit was used in the past for V3D_TRANSFORM_SNAP, which is now deprecated. 
11689          * Here we clear it for old files so they don't come in with V3D_RENDER_OVERRIDE set,
11690          * which would cause cameras, lamps, etc to become invisible */
11691         for(sc= main->screen.first; sc; sc= sc->id.next) {
11692             ScrArea *sa;
11693             for(sa= sc->areabase.first; sa; sa= sa->next) {
11694                 SpaceLink *sl;
11695                 for (sl= sa->spacedata.first; sl; sl= sl->next) {
11696                     if(sl->spacetype==SPACE_VIEW3D) {
11697                         View3D* v3d = (View3D *)sl;
11698                         v3d->flag2 &= ~V3D_RENDER_OVERRIDE;
11699                     }
11700                 }
11701             }
11702         }
11703     }
11704 
11705     if (main->versionfile < 252 || (main->versionfile == 252 && main->subversionfile < 1)) {
11706         Brush *brush;
11707         Object *ob;
11708         Scene *scene;
11709         bNodeTree *ntree;
11710         
11711         for (brush= main->brush.first; brush; brush= brush->id.next) {
11712             if (brush->curve) brush->curve->preset = CURVE_PRESET_SMOOTH;
11713         }
11714         
11715         /* properly initialise active flag for fluidsim modifiers */
11716         for(ob = main->object.first; ob; ob = ob->id.next) {
11717             ModifierData *md;
11718             for(md= ob->modifiers.first; md; md= md->next) {
11719                 if (md->type == eModifierType_Fluidsim) {
11720                     FluidsimModifierData *fmd = (FluidsimModifierData *)md;
11721                     fmd->fss->flag |= OB_FLUIDSIM_ACTIVE; 
11722                     fmd->fss->flag |= OB_FLUIDSIM_OVERRIDE_TIME;
11723                 }
11724             }
11725         }
11726         
11727         /* adjustment to color balance node values */
11728         for(scene= main->scene.first; scene; scene= scene->id.next) {
11729             if(scene->nodetree) {
11730                 bNode *node=scene->nodetree->nodes.first;
11731                 
11732                 while(node) {
11733                     if (node->type == CMP_NODE_COLORBALANCE) {
11734                         NodeColorBalance *n= (NodeColorBalance *)node->storage;
11735                         n->lift[0] += 1.f;
11736                         n->lift[1] += 1.f;
11737                         n->lift[2] += 1.f;
11738                     }
11739                     node= node->next;
11740                 }
11741             }
11742         }
11743         /* check inside node groups too */
11744         for (ntree= main->nodetree.first; ntree; ntree=ntree->id.next) {
11745             bNode *node=ntree->nodes.first;
11746             
11747             while(node) {
11748                 if (node->type == CMP_NODE_COLORBALANCE) {
11749                     NodeColorBalance *n= (NodeColorBalance *)node->storage;
11750                     n->lift[0] += 1.f;
11751                     n->lift[1] += 1.f;
11752                     n->lift[2] += 1.f;
11753                 }
11754                 node= node->next;
11755             }
11756         }
11757     }
11758     
11759     /* old-track -> constraints (this time we're really doing it!) */
11760     if (main->versionfile < 252 || (main->versionfile == 252 && main->subversionfile < 2)) {
11761         Object *ob;
11762         
11763         for (ob = main->object.first; ob; ob = ob->id.next)
11764             do_version_old_trackto_to_constraints(ob);
11765     }
11766     
11767     if (main->versionfile < 252 || (main->versionfile == 252 && main->subversionfile < 5)) {
11768         bScreen *sc;
11769         
11770         /* Image editor scopes */
11771         for(sc= main->screen.first; sc; sc= sc->id.next) {
11772             ScrArea *sa;
11773             for(sa= sc->areabase.first; sa; sa= sa->next) {
11774                 SpaceLink *sl;
11775                 for (sl= sa->spacedata.first; sl; sl= sl->next) {
11776                     if(sl->spacetype==SPACE_IMAGE) {
11777                         SpaceImage *sima = (SpaceImage *)sl;
11778                         scopes_new(&sima->scopes);
11779                     }
11780                 }
11781             }
11782         }
11783     }
11784     
11785 
11786     if (main->versionfile < 253)
11787     {
11788         Object *ob;
11789         Scene *scene;
11790         bScreen *sc;
11791         Tex *tex;
11792         Brush *brush;
11793 
11794         for (sc= main->screen.first; sc; sc= sc->id.next) {
11795             ScrArea *sa;
11796             for (sa= sc->areabase.first; sa; sa= sa->next) {
11797                 SpaceLink *sl;
11798                 for (sl= sa->spacedata.first; sl; sl= sl->next) {
11799                     if (sl->spacetype == SPACE_NODE) {
11800                         SpaceNode *snode= (SpaceNode *)sl;
11801                         ListBase *regionbase;
11802                         ARegion *ar;
11803 
11804                         if (sl == sa->spacedata.first)
11805                             regionbase = &sa->regionbase;
11806                         else
11807                             regionbase = &sl->regionbase;
11808 
11809                         if (snode->v2d.minzoom > 0.09f)
11810                             snode->v2d.minzoom= 0.09f;
11811                         if (snode->v2d.maxzoom < 2.31f)
11812                             snode->v2d.maxzoom= 2.31f;
11813 
11814                         for (ar= regionbase->first; ar; ar= ar->next) {
11815                             if (ar->regiontype == RGN_TYPE_WINDOW) {
11816                                 if (ar->v2d.minzoom > 0.09f)
11817                                     ar->v2d.minzoom= 0.09f;
11818                                 if (ar->v2d.maxzoom < 2.31f)
11819                                     ar->v2d.maxzoom= 2.31f;
11820                             }
11821                         }
11822                     }
11823                     else if (sl->spacetype == SPACE_TIME) {
11824                         SpaceTime *stime= (SpaceTime *)sl;
11825                         
11826                         /* enable all cache display */
11827                         stime->cache_display |= TIME_CACHE_DISPLAY;
11828                         stime->cache_display |= (TIME_CACHE_SOFTBODY|TIME_CACHE_PARTICLES);
11829                         stime->cache_display |= (TIME_CACHE_CLOTH|TIME_CACHE_SMOKE|TIME_CACHE_DYNAMICPAINT);
11830                     }
11831                 }
11832             }
11833         }
11834 
11835         do_version_mdef_250(main);
11836 
11837         /* parent type to modifier */
11838         for(ob = main->object.first; ob; ob = ob->id.next) {
11839             if(ob->parent) {
11840                 Object *parent= (Object *)newlibadr(fd, lib, ob->parent);
11841                 if(parent) { /* parent may not be in group */
11842                     if(parent->type==OB_ARMATURE && ob->partype==PARSKEL) {
11843                         ArmatureModifierData *amd;
11844                         bArmature *arm= (bArmature *)newlibadr(fd, lib, parent->data);
11845 
11846                         amd = (ArmatureModifierData*) modifier_new(eModifierType_Armature);
11847                         amd->object = ob->parent;
11848                         BLI_addtail((ListBase*)&ob->modifiers, amd);
11849                         amd->deformflag= arm->deformflag;
11850                         ob->partype = PAROBJECT;
11851                     }
11852                     else if(parent->type==OB_LATTICE && ob->partype==PARSKEL) {
11853                         LatticeModifierData *lmd;
11854 
11855                         lmd = (LatticeModifierData*) modifier_new(eModifierType_Lattice);
11856                         lmd->object = ob->parent;
11857                         BLI_addtail((ListBase*)&ob->modifiers, lmd);
11858                         ob->partype = PAROBJECT;
11859                     }
11860                     else if(parent->type==OB_CURVE && ob->partype==PARCURVE) {
11861                         CurveModifierData *cmd;
11862 
11863                         cmd = (CurveModifierData*) modifier_new(eModifierType_Curve);
11864                         cmd->object = ob->parent;
11865                         BLI_addtail((ListBase*)&ob->modifiers, cmd);
11866                         ob->partype = PAROBJECT;
11867                     }
11868                 }
11869             }
11870         }
11871         
11872         /* initialise scene active layer */
11873         for (scene= main->scene.first; scene; scene=scene->id.next) {
11874             int i;
11875             for(i=0; i<20; i++) {
11876                 if(scene->lay & (1<<i)) {
11877                     scene->layact= 1<<i;
11878                     break;
11879                 }
11880             }
11881         }
11882 
11883         for(tex= main->tex.first; tex; tex= tex->id.next) {
11884             /* if youre picky, this isn't correct until we do a version bump
11885              * since you could set saturation to be 0.0*/
11886             if(tex->saturation==0.0f)
11887                 tex->saturation= 1.0f;
11888         }
11889 
11890         {
11891             Curve *cu;
11892             for(cu= main->curve.first; cu; cu= cu->id.next) {
11893                 cu->smallcaps_scale= 0.75f;
11894             }
11895         }
11896 
11897         for (scene= main->scene.first; scene; scene=scene->id.next) {
11898             if(scene) {
11899                 Sequence *seq;
11900                 SEQ_BEGIN(scene->ed, seq) {
11901                     if(seq->sat==0.0f) {
11902                         seq->sat= 1.0f;
11903                     }
11904                 }
11905                 SEQ_END
11906             }
11907         }
11908 
11909         /* GSOC 2010 Sculpt - New settings for Brush */
11910 
11911         for (brush= main->brush.first; brush; brush= brush->id.next) {
11912             /* Sanity Check */
11913 
11914             // infinite number of dabs
11915             if (brush->spacing == 0)
11916                 brush->spacing = 10;
11917 
11918             // will have no effect
11919             if (brush->alpha == 0)
11920                 brush->alpha = 0.5f;
11921 
11922             // bad radius
11923             if (brush->unprojected_radius == 0)
11924                 brush->unprojected_radius = 0.125f;
11925 
11926             // unusable size
11927             if (brush->size == 0)
11928                 brush->size = 35;
11929 
11930             // can't see overlay
11931             if (brush->texture_overlay_alpha == 0)
11932                 brush->texture_overlay_alpha = 33;
11933 
11934             // same as draw brush
11935             if (brush->crease_pinch_factor == 0)
11936                 brush->crease_pinch_factor = 0.5f;
11937 
11938             // will sculpt no vertexes
11939             if (brush->plane_trim == 0)
11940                 brush->plane_trim = 0.5f;
11941 
11942             // same as smooth stroke off
11943             if (brush->smooth_stroke_radius == 0)
11944                 brush->smooth_stroke_radius= 75;
11945 
11946             // will keep cursor in one spot
11947             if (brush->smooth_stroke_radius == 1)
11948                 brush->smooth_stroke_factor= 0.9f;
11949 
11950             // same as dots
11951             if (brush->rate == 0)
11952                 brush->rate = 0.1f;
11953 
11954             /* New Settings */
11955             if (main->versionfile < 252 || (main->versionfile == 252 && main->subversionfile < 5)) {
11956                 brush->flag |= BRUSH_SPACE_ATTEN; // explicitly enable adaptive space
11957 
11958                 // spacing was originally in pixels, convert it to percentage for new version
11959                 // size should not be zero due to sanity check above
11960                 brush->spacing = (int)(100*((float)brush->spacing) / ((float)brush->size));
11961 
11962                 if (brush->add_col[0] == 0 &&
11963                     brush->add_col[1] == 0 &&
11964                     brush->add_col[2] == 0)
11965                 {
11966                     brush->add_col[0] = 1.00f;
11967                     brush->add_col[1] = 0.39f;
11968                     brush->add_col[2] = 0.39f;
11969                 }
11970 
11971                 if (brush->sub_col[0] == 0 &&
11972                     brush->sub_col[1] == 0 &&
11973                     brush->sub_col[2] == 0)
11974                 {
11975                     brush->sub_col[0] = 0.39f;
11976                     brush->sub_col[1] = 0.39f;
11977                     brush->sub_col[2] = 1.00f;
11978                 }
11979             }
11980         }
11981     }
11982 
11983     /* GSOC Sculpt 2010 - Sanity check on Sculpt/Paint settings */
11984     if (main->versionfile < 253) {
11985         Scene *sce;
11986         for (sce= main->scene.first; sce; sce= sce->id.next) {
11987             if (sce->toolsettings->sculpt_paint_unified_alpha == 0)
11988                 sce->toolsettings->sculpt_paint_unified_alpha = 0.5f;
11989 
11990             if (sce->toolsettings->sculpt_paint_unified_unprojected_radius == 0) 
11991                 sce->toolsettings->sculpt_paint_unified_unprojected_radius = 0.125f;
11992 
11993             if (sce->toolsettings->sculpt_paint_unified_size == 0)
11994                 sce->toolsettings->sculpt_paint_unified_size = 35;
11995         }
11996     }
11997 
11998     if (main->versionfile < 253 || (main->versionfile == 253 && main->subversionfile < 1))
11999         {
12000             Object *ob;
12001 
12002             for(ob = main->object.first; ob; ob = ob->id.next) {
12003                 ModifierData *md;
12004                 for(md= ob->modifiers.first; md; md= md->next) {
12005                     if (md->type == eModifierType_Smoke) {
12006                         SmokeModifierData *smd = (SmokeModifierData *)md;
12007 
12008                         if((smd->type & MOD_SMOKE_TYPE_DOMAIN) && smd->domain)
12009                         {
12010                             smd->domain->vorticity = 2.0f;
12011                             smd->domain->time_scale = 1.0f;
12012 
12013                             if(!(smd->domain->flags & (1<<4)))
12014                                 continue;
12015 
12016                             /* delete old MOD_SMOKE_INITVELOCITY flag */
12017                             smd->domain->flags &= ~(1<<4);
12018 
12019                             /* for now just add it to all flow objects in the scene */
12020                             {
12021                                 Object *ob2;
12022                                 for(ob2 = main->object.first; ob2; ob2 = ob2->id.next) {
12023                                     ModifierData *md2;
12024                                     for(md2= ob2->modifiers.first; md2; md2= md2->next) {
12025                                         if (md2->type == eModifierType_Smoke) {
12026                                             SmokeModifierData *smd2 = (SmokeModifierData *)md2;
12027 
12028                                             if((smd2->type & MOD_SMOKE_TYPE_FLOW) && smd2->flow)
12029                                             {
12030                                                 smd2->flow->flags |= MOD_SMOKE_FLOW_INITVELOCITY;
12031                                             }
12032                                         }
12033                                     }
12034                                 }
12035                             }
12036 
12037                         }
12038                         else if((smd->type & MOD_SMOKE_TYPE_FLOW) && smd->flow)
12039                         {
12040                             smd->flow->vel_multi = 1.0f;
12041                         }
12042 
12043                     }
12044                 }
12045             }
12046         }
12047 
12048     if (main->versionfile < 255 || (main->versionfile == 255 && main->subversionfile < 1)) {
12049         Brush *br;
12050         ParticleSettings *part;
12051         bScreen *sc;
12052         Object *ob;
12053 
12054         for(br= main->brush.first; br; br= br->id.next) {
12055             if(br->ob_mode==0)
12056                 br->ob_mode= OB_MODE_ALL_PAINT;
12057         }
12058 
12059         for(part = main->particle.first; part; part = part->id.next) {
12060             if(part->boids)
12061                 part->boids->pitch = 1.0f;
12062 
12063             part->flag &= ~PART_HAIR_REGROW; /* this was a deprecated flag before */
12064             part->kink_amp_clump = 1.f; /* keep old files looking similar */
12065         }
12066 
12067         for (sc= main->screen.first; sc; sc= sc->id.next) {
12068             ScrArea *sa;
12069             for (sa= sc->areabase.first; sa; sa= sa->next) {
12070                 SpaceLink *sl;
12071                 for (sl= sa->spacedata.first; sl; sl= sl->next) {
12072                     if (sl->spacetype == SPACE_INFO) {
12073                         SpaceInfo *sinfo= (SpaceInfo *)sl;
12074                         ARegion *ar;
12075 
12076                         sinfo->rpt_mask= INFO_RPT_OP;
12077 
12078                         for (ar= sa->regionbase.first; ar; ar= ar->next) {
12079                             if (ar->regiontype == RGN_TYPE_WINDOW) {
12080                                 ar->v2d.scroll = (V2D_SCROLL_RIGHT);
12081                                 ar->v2d.align = V2D_ALIGN_NO_NEG_X|V2D_ALIGN_NO_NEG_Y; /* align bottom left */
12082                                 ar->v2d.keepofs = V2D_LOCKOFS_X;
12083                                 ar->v2d.keepzoom = (V2D_LOCKZOOM_X|V2D_LOCKZOOM_Y|V2D_LIMITZOOM|V2D_KEEPASPECT);
12084                                 ar->v2d.keeptot= V2D_KEEPTOT_BOUNDS;
12085                                 ar->v2d.minzoom= ar->v2d.maxzoom= 1.0f;
12086                             }
12087                         }
12088                     }
12089                 }
12090             }
12091         }
12092 
12093         /* fix rotation actuators for objects so they use real angles (radians)
12094          * since before blender went opensource this strange scalar was used: (1 / 0.02) * 2 * math.pi/360 */
12095         for(ob= main->object.first; ob; ob= ob->id.next) {
12096             bActuator *act= ob->actuators.first;
12097             while(act) {
12098                 if (act->type==ACT_OBJECT) {
12099                     /* multiply velocity with 50 in old files */
12100                     bObjectActuator *oa= act->data;
12101                     mul_v3_fl(oa->drot, 0.8726646259971648f);
12102                 }
12103                 act= act->next;
12104             }
12105         }
12106     }
12107     
12108     // init facing axis property of steering actuators
12109     {                   
12110         Object *ob;
12111         for(ob = main->object.first; ob; ob = ob->id.next) {
12112             bActuator *act;
12113             for(act= ob->actuators.first; act; act= act->next) {
12114                 if(act->type==ACT_STEERING) {
12115                     bSteeringActuator* stact = act->data;
12116                     if (stact->facingaxis==0)
12117                     {
12118                         stact->facingaxis=1;
12119                     }                       
12120                 }
12121             }
12122         }
12123     }
12124 
12125     if (main->versionfile < 255 || (main->versionfile == 255 && main->subversionfile < 3)) {
12126         Object *ob;
12127 
12128         /* ocean res is now squared, reset old ones - will be massive */
12129         for(ob = main->object.first; ob; ob = ob->id.next) {
12130             ModifierData *md;
12131             for(md= ob->modifiers.first; md; md= md->next) {
12132                 if (md->type == eModifierType_Ocean) {
12133                     OceanModifierData *omd = (OceanModifierData *)md;
12134                     omd->resolution = 7;
12135                     omd->oceancache = NULL;
12136                 }
12137             }
12138         }       
12139     }
12140 
12141     if (main->versionfile < 256) {
12142         bScreen *sc;
12143         ScrArea *sa;
12144         Key *key;
12145         
12146         /* Fix for sample line scope initializing with no height */
12147         for(sc= main->screen.first; sc; sc= sc->id.next) {
12148             sa= sc->areabase.first;
12149             while(sa) {
12150                 SpaceLink *sl;
12151                 for (sl= sa->spacedata.first; sl; sl= sl->next) {
12152                     if(sl->spacetype==SPACE_IMAGE) {
12153                         SpaceImage *sima= (SpaceImage *)sl;
12154                         if (sima->sample_line_hist.height == 0 )
12155                             sima->sample_line_hist.height = 100;
12156                     }
12157                 }
12158                 sa= sa->next;
12159             }
12160         }
12161         
12162         /* old files could have been saved with slidermin = slidermax = 0.0, but the UI in
12163          * 2.4x would never reveal this to users as a dummy value always ended up getting used
12164          * instead
12165          */
12166         for (key = main->key.first; key; key = key->id.next) {
12167             KeyBlock *kb;
12168             
12169             for (kb = key->block.first; kb; kb = kb->next) {
12170                 if (IS_EQF(kb->slidermin, kb->slidermax) && IS_EQ(kb->slidermax, 0))
12171                     kb->slidermax = kb->slidermin + 1.0f;
12172             }
12173         }
12174     }
12175     
12176     if (main->versionfile < 256 || (main->versionfile == 256 && main->subversionfile < 1)) {
12177         /* fix for bones that didn't have arm_roll before */
12178         bArmature* arm;
12179         Bone* bone;
12180         Object *ob;
12181 
12182         for (arm = main->armature.first; arm; arm = arm->id.next)
12183             for (bone = arm->bonebase.first; bone; bone = bone->next)
12184                 do_version_bone_roll_256(bone);
12185 
12186         /* fix for objects which have zero dquat's
12187          * since this is multiplied with the quat rather than added */
12188         for(ob= main->object.first; ob; ob= ob->id.next) {
12189             if(is_zero_v4(ob->dquat)) {
12190                 unit_qt(ob->dquat);
12191             }
12192             if(is_zero_v3(ob->drotAxis) && ob->drotAngle == 0.0f) {
12193                 unit_axis_angle(ob->drotAxis, &ob->drotAngle);
12194             }
12195         }
12196     }
12197 
12198     if (main->versionfile < 256 || (main->versionfile == 256 && main->subversionfile < 2)) {
12199         bNodeTree *ntree;
12200         
12201         /* node sockets are not exposed automatically any more,
12202          * this mimics the old behaviour by adding all unlinked sockets to groups.
12203          */
12204         for (ntree=main->nodetree.first; ntree; ntree=ntree->id.next) {
12205             /* XXX Only setting a flag here. Actual adding of group sockets
12206              * is done in lib_verify_nodetree, because at this point the internal
12207              * nodes may not be up-to-date! (missing lib-link)
12208              */
12209             ntree->flag |= NTREE_DO_VERSIONS_GROUP_EXPOSE;
12210         }
12211     }
12212 
12213     if (main->versionfile < 256 || (main->versionfile == 256 && main->subversionfile <3)){
12214         bScreen *sc;
12215         Brush *brush;
12216         Object *ob;
12217         ParticleSettings *part;
12218         Material *mat;
12219         int tex_nr, transp_tex;
12220         
12221         for(mat = main->mat.first; mat; mat = mat->id.next){
12222             if(!(mat->mode & MA_TRANSP) && !(mat->material_type & MA_TYPE_VOLUME)){
12223                 
12224                 transp_tex= 0;
12225                 
12226                 for(tex_nr=0; tex_nr<MAX_MTEX; tex_nr++){
12227                     if(!mat->mtex[tex_nr]) continue;
12228                     if(mat->mtex[tex_nr]->mapto & MAP_ALPHA) transp_tex= 1;
12229                 }
12230 
12231                 /* weak! material alpha could be animated */
12232                 if(mat->alpha < 1.0f || mat->fresnel_tra > 0.0f || transp_tex){
12233                     mat->mode |= MA_TRANSP;
12234                     mat->mode &= ~(MA_ZTRANSP|MA_RAYTRANSP);
12235                 }
12236             }
12237         }
12238 
12239         /* redraws flag in SpaceTime has been moved to Screen level */
12240         for (sc = main->screen.first; sc; sc= sc->id.next) {
12241             if (sc->redraws_flag == 0) {
12242                 /* just initialise to default? */
12243                 // XXX: we could also have iterated through areas, and taken them from the first timeline available...
12244                 sc->redraws_flag = TIME_ALL_3D_WIN|TIME_ALL_ANIM_WIN;
12245             }
12246         }
12247 
12248         for (brush= main->brush.first; brush; brush= brush->id.next) {
12249             if(brush->height == 0)
12250                 brush->height= 0.4f;
12251         }
12252 
12253         /* replace 'rim material' option for in offset*/
12254         for(ob = main->object.first; ob; ob = ob->id.next) {
12255             ModifierData *md;
12256             for(md= ob->modifiers.first; md; md= md->next) {
12257                 if (md->type == eModifierType_Solidify) {
12258                     SolidifyModifierData *smd = (SolidifyModifierData *)md;
12259                     if(smd->flag & MOD_SOLIDIFY_RIM_MATERIAL) {
12260                         smd->mat_ofs_rim= 1;
12261                         smd->flag &= ~MOD_SOLIDIFY_RIM_MATERIAL;
12262                     }
12263                 }
12264             }
12265         }
12266 
12267         /* particle draw color from material */
12268         for(part = main->particle.first; part; part = part->id.next) {
12269             if(part->draw & PART_DRAW_MAT_COL)
12270                 part->draw_col = PART_DRAW_COL_MAT;
12271         }
12272     }
12273 
12274     if (main->versionfile < 256 || (main->versionfile == 256 && main->subversionfile < 6)){
12275         Mesh *me;
12276 
12277         for(me= main->mesh.first; me; me= me->id.next)
12278             mesh_calc_normals(me->mvert, me->totvert, me->mface, me->totface, NULL);
12279     }
12280 
12281     if (main->versionfile < 256 || (main->versionfile == 256 && main->subversionfile < 2)){
12282         /* update blur area sizes from 0..1 range to 0..100 percentage */
12283         Scene *scene;
12284         bNode *node;
12285         for (scene=main->scene.first; scene; scene=scene->id.next)
12286             if (scene->nodetree)
12287                 for (node=scene->nodetree->nodes.first; node; node=node->next)
12288                     if (node->type==CMP_NODE_BLUR) {
12289                         NodeBlurData *nbd= node->storage;
12290                         nbd->percentx *= 100.0f;
12291                         nbd->percenty *= 100.0f;
12292                     }
12293     }
12294 
12295     if (main->versionfile < 258 || (main->versionfile == 258 && main->subversionfile < 1)){
12296         /* screen view2d settings were not properly initialized [#27164]
12297          * v2d->scroll caused the bug but best reset other values too which are in old blend files only.
12298          * need to make less ugly - possibly an iterator? */
12299         bScreen *screen;
12300         for(screen= main->screen.first; screen; screen= screen->id.next) {
12301             ScrArea *sa;
12302             /* add regions */
12303             for(sa= screen->areabase.first; sa; sa= sa->next) {
12304                 SpaceLink *sl= sa->spacedata.first;
12305                 if(sl->spacetype==SPACE_IMAGE) {
12306                     ARegion *ar;
12307                     for (ar=sa->regionbase.first; ar; ar= ar->next) {
12308                         if(ar->regiontype == RGN_TYPE_WINDOW) {
12309                             View2D *v2d= &ar->v2d;
12310                             v2d->minzoom= v2d->maxzoom= v2d->scroll= v2d->keeptot= v2d->keepzoom= v2d->keepofs= v2d->align= 0;
12311                         }
12312                     }
12313                 }
12314                 for (sl= sa->spacedata.first; sl; sl= sl->next) {
12315                     if(sl->spacetype==SPACE_IMAGE) {
12316                         ARegion *ar;
12317                         for (ar=sl->regionbase.first; ar; ar= ar->next) {
12318                             if(ar->regiontype == RGN_TYPE_WINDOW) {
12319                                 View2D *v2d= &ar->v2d;
12320                                 v2d->minzoom= v2d->maxzoom= v2d->scroll= v2d->keeptot= v2d->keepzoom= v2d->keepofs= v2d->align= 0;
12321                             }
12322                         }
12323                     }
12324                 }
12325             }
12326         }
12327 
12328         {
12329             /* Initialize texture point density curve falloff */
12330             Tex *tex;
12331             for(tex= main->tex.first; tex; tex= tex->id.next) {
12332                 if(tex->pd) {
12333                     if (tex->pd->falloff_speed_scale == 0.0f)
12334                         tex->pd->falloff_speed_scale = 100.0f;
12335                     
12336                     if (!tex->pd->falloff_curve) {
12337                         tex->pd->falloff_curve = curvemapping_add(1, 0, 0, 1, 1);
12338                         
12339                         tex->pd->falloff_curve->preset = CURVE_PRESET_LINE;
12340                         tex->pd->falloff_curve->cm->flag &= ~CUMA_EXTEND_EXTRAPOLATE;
12341                         curvemap_reset(tex->pd->falloff_curve->cm, &tex->pd->falloff_curve->clipr, tex->pd->falloff_curve->preset, CURVEMAP_SLOPE_POSITIVE);
12342                         curvemapping_changed(tex->pd->falloff_curve, 0);
12343                     }
12344                 }
12345             }
12346         }
12347 
12348         {
12349             /* add default value for behind strength of camera actuator */
12350             Object *ob;
12351             bActuator *act;
12352             for(ob = main->object.first; ob; ob= ob->id.next) {
12353                 for(act= ob->actuators.first; act; act= act->next) {
12354                     if (act->type == ACT_CAMERA) {
12355                         bCameraActuator *ba= act->data;
12356 
12357                         ba->damping = 1.0/32.0;
12358                     }
12359                 }
12360             }
12361         }
12362 
12363         {
12364             ParticleSettings *part;
12365             for(part = main->particle.first; part; part = part->id.next) {
12366                 /* Initialize particle billboard scale */
12367                 part->bb_size[0] = part->bb_size[1] = 1.0f;
12368             }
12369         }
12370     }
12371 
12372     if (main->versionfile < 259 || (main->versionfile == 259 && main->subversionfile < 1)){
12373         {
12374             Scene *scene;
12375             Sequence *seq;
12376 
12377             for (scene=main->scene.first; scene; scene=scene->id.next)
12378             {
12379                 scene->r.ffcodecdata.audio_channels = 2;
12380                 scene->audio.volume = 1.0f;
12381                 SEQ_BEGIN(scene->ed, seq) {
12382                     seq->pitch = 1.0f;
12383                 }
12384                 SEQ_END
12385             }
12386         }
12387         {
12388             bScreen *screen;
12389             for(screen= main->screen.first; screen; screen= screen->id.next) {
12390                 ScrArea *sa;
12391                 /* add regions */
12392                 for(sa= screen->areabase.first; sa; sa= sa->next) {
12393                     SpaceLink *sl= sa->spacedata.first;
12394                     if(sl->spacetype==SPACE_SEQ) {
12395                         ARegion *ar;
12396                         for (ar=sa->regionbase.first; ar; ar= ar->next) {
12397                             if(ar->regiontype == RGN_TYPE_WINDOW) {
12398                                 if(ar->v2d.min[1] == 4.0f)
12399                                     ar->v2d.min[1]= 0.5f;
12400                             }
12401                         }
12402                     }
12403                     for (sl= sa->spacedata.first; sl; sl= sl->next) {
12404                         if(sl->spacetype==SPACE_SEQ) {
12405                             ARegion *ar;
12406                             for (ar=sl->regionbase.first; ar; ar= ar->next) {
12407                                 if(ar->regiontype == RGN_TYPE_WINDOW) {
12408                                     if(ar->v2d.min[1] == 4.0f)
12409                                         ar->v2d.min[1]= 0.5f;
12410                                 }
12411                             }
12412                         }
12413                     }
12414                 }
12415             }
12416         }
12417         {
12418             /* Make "auto-clamped" handles a per-keyframe setting instead of per-FCurve 
12419              *
12420              * We're only patching F-Curves in Actions here, since it is assumed that most
12421              * drivers out there won't be using this (and if they are, they're in the minority).
12422              * While we should aim to fix everything ideally, in practice it's far too hard
12423              * to get to every animdata block, not to mention the performance hit that'd have
12424              */
12425             bAction *act;
12426             FCurve *fcu;
12427             
12428             for (act = main->action.first; act; act = act->id.next) {
12429                 for (fcu = act->curves.first; fcu; fcu = fcu->next) {
12430                     BezTriple *bezt;
12431                     unsigned int i = 0;
12432                     
12433                     /* only need to touch curves that had this flag set */
12434                     if ((fcu->flag & FCURVE_AUTO_HANDLES) == 0)
12435                         continue;
12436                     if ((fcu->totvert == 0) || (fcu->bezt == NULL))
12437                         continue;
12438                         
12439                     /* only change auto-handles to auto-clamped */
12440                     for (bezt=fcu->bezt; i < fcu->totvert; i++, bezt++) {
12441                         if (bezt->h1 == HD_AUTO) bezt->h1 = HD_AUTO_ANIM;
12442                         if (bezt->h2 == HD_AUTO) bezt->h2 = HD_AUTO_ANIM;
12443                     }
12444                     
12445                     fcu->flag &= ~FCURVE_AUTO_HANDLES;
12446                 }
12447             }
12448         }
12449         {
12450             /* convert fcurve and shape action actuators to action actuators */
12451             Object *ob;
12452             bActuator *act;
12453             bIpoActuator *ia;
12454             bActionActuator *aa;
12455 
12456             for (ob= main->object.first; ob; ob= ob->id.next) {
12457                 for (act= ob->actuators.first; act; act= act->next) {
12458                     if (act->type == ACT_IPO) {
12459                         // Create the new actuator
12460                         ia= act->data;
12461                         aa= MEM_callocN(sizeof(bActionActuator), "fcurve -> action actuator do_version");
12462 
12463                         // Copy values
12464                         aa->type = ia->type;
12465                         aa->flag = ia->flag;
12466                         aa->sta = ia->sta;
12467                         aa->end = ia->end;
12468                         BLI_strncpy(aa->name, ia->name, sizeof(aa->name));
12469                         BLI_strncpy(aa->frameProp, ia->frameProp, sizeof(aa->frameProp));
12470                         if (ob->adt)
12471                             aa->act = ob->adt->action;
12472 
12473                         // Get rid of the old actuator
12474                         MEM_freeN(ia);
12475 
12476                         // Assign the new actuator
12477                         act->data = aa;
12478                         act->type= act->otype= ACT_ACTION;
12479                         
12480                     }
12481                     else if (act->type == ACT_SHAPEACTION)  {
12482                         act->type = act->otype = ACT_ACTION;
12483                     }
12484                 }
12485             }
12486         }
12487     }
12488 
12489     if (main->versionfile < 259 || (main->versionfile == 259 && main->subversionfile < 2)){
12490         {
12491             /* Convert default socket values from bNodeStack */
12492             Scene *sce;
12493             Material *mat;
12494             Tex *tex;
12495             bNodeTree *ntree;
12496             for (ntree=main->nodetree.first; ntree; ntree=ntree->id.next) {
12497                 do_versions_nodetree_default_value(ntree);
12498                 ntree->update |= NTREE_UPDATE;
12499             }
12500             for (sce=main->scene.first; sce; sce=sce->id.next)
12501                 if (sce->nodetree) {
12502                 do_versions_nodetree_default_value(sce->nodetree);
12503                 sce->nodetree->update |= NTREE_UPDATE;
12504             }
12505             for (mat=main->mat.first; mat; mat=mat->id.next)
12506                 if (mat->nodetree) {
12507                 do_versions_nodetree_default_value(mat->nodetree);
12508                 mat->nodetree->update |= NTREE_UPDATE;
12509             }
12510             for (tex=main->tex.first; tex; tex=tex->id.next)
12511                 if (tex->nodetree) {
12512                 do_versions_nodetree_default_value(tex->nodetree);
12513                 tex->nodetree->update |= NTREE_UPDATE;
12514             }
12515         }
12516 
12517         /* add SOCK_DYNAMIC flag to existing group sockets */
12518         {
12519             bNodeTree *ntree;
12520             /* only need to do this for trees in main, local trees are not used as groups */
12521             for (ntree=main->nodetree.first; ntree; ntree=ntree->id.next) {
12522                 do_versions_nodetree_dynamic_sockets(ntree);
12523                 ntree->update |= NTREE_UPDATE;
12524             }
12525         }
12526 
12527         {
12528             /* Initialize group tree nodetypes.
12529              * These are used to distinguish tree types and
12530              * associate them with specific node types for polling.
12531              */
12532             bNodeTree *ntree;
12533             /* all node trees in main->nodetree are considered groups */
12534             for (ntree=main->nodetree.first; ntree; ntree=ntree->id.next)
12535                 ntree->nodetype = NODE_GROUP;
12536         }
12537     }
12538 
12539     if (main->versionfile < 259 || (main->versionfile == 259 && main->subversionfile < 4)){
12540         {
12541             /* Adaptive time step for particle systems */
12542             ParticleSettings *part;
12543             for (part = main->particle.first; part; part = part->id.next) {
12544                 part->courant_target = 0.2f;
12545                 part->time_flag &= ~PART_TIME_AUTOSF;
12546             }
12547         }
12548 
12549         {
12550             /* set defaults for obstacle avoidance, recast data */
12551             Scene *sce;
12552             for(sce = main->scene.first; sce; sce = sce->id.next)
12553             {
12554                 if (sce->gm.levelHeight == 0.f)
12555                     sce->gm.levelHeight = 2.f;
12556 
12557                 if(sce->gm.recastData.cellsize == 0.0f)
12558                     sce->gm.recastData.cellsize = 0.3f;
12559                 if(sce->gm.recastData.cellheight == 0.0f)
12560                     sce->gm.recastData.cellheight = 0.2f;
12561                 if(sce->gm.recastData.agentmaxslope == 0.0f)
12562                     sce->gm.recastData.agentmaxslope = (float)M_PI/4;
12563                 if(sce->gm.recastData.agentmaxclimb == 0.0f)
12564                     sce->gm.recastData.agentmaxclimb = 0.9f;
12565                 if(sce->gm.recastData.agentheight == 0.0f)
12566                     sce->gm.recastData.agentheight = 2.0f;
12567                 if(sce->gm.recastData.agentradius == 0.0f)
12568                     sce->gm.recastData.agentradius = 0.6f;
12569                 if(sce->gm.recastData.edgemaxlen == 0.0f)
12570                     sce->gm.recastData.edgemaxlen = 12.0f;
12571                 if(sce->gm.recastData.edgemaxerror == 0.0f)
12572                     sce->gm.recastData.edgemaxerror = 1.3f;
12573                 if(sce->gm.recastData.regionminsize == 0.0f)
12574                     sce->gm.recastData.regionminsize = 8.f;
12575                 if(sce->gm.recastData.regionmergesize == 0.0f)
12576                     sce->gm.recastData.regionmergesize = 20.f;
12577                 if(sce->gm.recastData.vertsperpoly<3)
12578                     sce->gm.recastData.vertsperpoly = 6;
12579                 if(sce->gm.recastData.detailsampledist == 0.0f)
12580                     sce->gm.recastData.detailsampledist = 6.0f;
12581                 if(sce->gm.recastData.detailsamplemaxerror == 0.0f)
12582                     sce->gm.recastData.detailsamplemaxerror = 1.0f;
12583             }
12584         }
12585     }
12586 
12587     if (main->versionfile < 260){
12588         {
12589             /* set default alpha value of Image outputs in image and render layer nodes to 0 */
12590             Scene *sce;
12591             bNodeTree *ntree;
12592             
12593             for (sce=main->scene.first; sce; sce=sce->id.next) {
12594                 /* there are files with invalid audio_channels value, the real cause
12595                    is unknown, but we fix it here anyway to avoid crashes */
12596                 if(sce->r.ffcodecdata.audio_channels == 0)
12597                     sce->r.ffcodecdata.audio_channels = 2;
12598 
12599                 if (sce->nodetree)
12600                     do_versions_nodetree_image_default_alpha_output(sce->nodetree);
12601             }
12602 
12603             for (ntree=main->nodetree.first; ntree; ntree=ntree->id.next)
12604                 do_versions_nodetree_image_default_alpha_output(ntree);
12605         }
12606 
12607         {
12608             /* support old particle dupliobject rotation settings */
12609             ParticleSettings *part;
12610 
12611             for (part=main->particle.first; part; part=part->id.next) {
12612                 if(ELEM(part->ren_as, PART_DRAW_OB, PART_DRAW_GR)) {
12613                     part->draw |= PART_DRAW_ROTATE_OB;
12614 
12615                     if(part->rotmode == 0)
12616                         part->rotmode = PART_ROT_VEL;
12617                 }
12618             }
12619         }
12620     }
12621 
12622     if (main->versionfile < 260 || (main->versionfile == 260 && main->subversionfile < 1)){
12623         Object *ob;
12624 
12625         for (ob= main->object.first; ob; ob= ob->id.next) {
12626             ob->collision_boundtype= ob->boundtype;
12627         }
12628 
12629         {
12630             Camera *cam;
12631             for(cam= main->camera.first; cam; cam= cam->id.next) {
12632                 if (cam->sensor_x < 0.01f)
12633                     cam->sensor_x = DEFAULT_SENSOR_WIDTH;
12634 
12635                 if (cam->sensor_y < 0.01f)
12636                     cam->sensor_y = DEFAULT_SENSOR_HEIGHT;
12637             }
12638         }
12639     }
12640 
12641     if (main->versionfile < 260 || (main->versionfile == 260 && main->subversionfile < 2)) {
12642         bNodeTreeType *ntreetype= ntreeGetType(NTREE_SHADER);
12643 
12644         if(ntreetype && ntreetype->foreach_nodetree)
12645             ntreetype->foreach_nodetree(main, NULL, do_version_ntree_tex_mapping_260);
12646     }
12647 
12648     if (main->versionfile < 260 || (main->versionfile == 260 && main->subversionfile < 4)){
12649         {
12650             /* Convert node angles to radians! */
12651             Scene *sce;
12652             Material *mat;
12653             bNodeTree *ntree;
12654 
12655             for (sce=main->scene.first; sce; sce=sce->id.next) {
12656                 if (sce->nodetree)
12657                     do_versions_nodetree_convert_angle(sce->nodetree);
12658             }
12659 
12660             for (mat=main->mat.first; mat; mat=mat->id.next) {
12661                 if (mat->nodetree)
12662                     do_versions_nodetree_convert_angle(mat->nodetree);
12663             }
12664 
12665             for (ntree=main->nodetree.first; ntree; ntree=ntree->id.next)
12666                 do_versions_nodetree_convert_angle(ntree);
12667         }
12668 
12669         {
12670             /* Tomato compatibility code. */
12671             bScreen *sc;
12672             MovieClip *clip;
12673 
12674             for (sc= main->screen.first; sc; sc= sc->id.next) {
12675                 ScrArea *sa;
12676                 for (sa= sc->areabase.first; sa; sa= sa->next) {
12677                     SpaceLink *sl;
12678                     for (sl= sa->spacedata.first; sl; sl= sl->next) {
12679                         if(sl->spacetype==SPACE_VIEW3D) {
12680                             View3D *v3d= (View3D *)sl;
12681                             if(v3d->bundle_size==0.0f) {
12682                                 v3d->bundle_size= 0.2f;
12683                                 v3d->flag2 |= V3D_SHOW_RECONSTRUCTION;
12684                             }
12685                             else if(sl->spacetype==SPACE_CLIP) {
12686                                 SpaceClip *sc= (SpaceClip *)sl;
12687                                 if(sc->scopes.track_preview_height==0)
12688                                     sc->scopes.track_preview_height= 120;
12689                             }
12690 
12691                             if(v3d->bundle_drawtype==0)
12692                                 v3d->bundle_drawtype= OB_PLAINAXES;
12693                         }
12694                     }
12695                 }
12696             }
12697 
12698             for (clip= main->movieclip.first; clip; clip= clip->id.next) {
12699                 MovieTrackingTrack *track;
12700 
12701                 if(clip->aspx<1.0f) {
12702                     clip->aspx= 1.0f;
12703                     clip->aspy= 1.0f;
12704                 }
12705 
12706                 clip->proxy.build_tc_flag= IMB_TC_RECORD_RUN |
12707                                            IMB_TC_FREE_RUN |
12708                                            IMB_TC_INTERPOLATED_REC_DATE_FREE_RUN;
12709 
12710                 if(clip->proxy.build_size_flag==0)
12711                     clip->proxy.build_size_flag= IMB_PROXY_25;
12712 
12713                 if(clip->proxy.quality==0)
12714                     clip->proxy.quality= 90;
12715 
12716                 if(clip->tracking.camera.pixel_aspect<0.01f)
12717                     clip->tracking.camera.pixel_aspect= 1.f;
12718 
12719                 track= clip->tracking.tracks.first;
12720                 while(track) {
12721                     if(track->pyramid_levels==0)
12722                         track->pyramid_levels= 2;
12723 
12724                     if(track->minimum_correlation==0.0f)
12725                         track->minimum_correlation= 0.75f;
12726 
12727                     track= track->next;
12728                 }
12729             }
12730         }
12731     }
12732 
12733     if (main->versionfile < 260 || (main->versionfile == 260 && main->subversionfile < 6))
12734     {
12735         Scene *sce;
12736         MovieClip *clip;
12737         bScreen *sc;
12738 
12739         for(sce = main->scene.first; sce; sce = sce->id.next) {
12740             do_versions_image_settings_2_60(sce);
12741         }
12742 
12743         for (clip= main->movieclip.first; clip; clip= clip->id.next) {
12744             MovieTrackingSettings *settings= &clip->tracking.settings;
12745 
12746             if(settings->default_pyramid_levels==0) {
12747                 settings->default_tracker= TRACKER_KLT;
12748                 settings->default_pyramid_levels= 2;
12749                 settings->default_minimum_correlation= 0.75;
12750                 settings->default_pattern_size= 11;
12751                 settings->default_search_size= 51;
12752             }
12753         }
12754 
12755         for (sc= main->screen.first; sc; sc= sc->id.next) {
12756             ScrArea *sa;
12757             for (sa= sc->areabase.first; sa; sa= sa->next) {
12758                 SpaceLink *sl;
12759                 for (sl= sa->spacedata.first; sl; sl= sl->next) {
12760                     if(sl->spacetype==SPACE_VIEW3D) {
12761                         View3D *v3d= (View3D *)sl;
12762                         v3d->flag2&= ~V3D_RENDER_SHADOW;
12763                     }
12764                 }
12765             }
12766         }
12767 
12768         {
12769             Object *ob;
12770             for (ob= main->object.first; ob; ob= ob->id.next) {
12771                 /* convert delta addition into delta scale */
12772                 int i;
12773                 for (i= 0; i < 3; i++) {
12774                     if ( (ob->dsize[i] == 0.0f) || /* simple case, user never touched dsize */
12775                          (ob->size[i]  == 0.0f))   /* cant scale the dsize to give a non zero result, so fallback to 1.0f */
12776                     {
12777                         ob->dscale[i]= 1.0f;
12778                     }
12779                     else {
12780                         ob->dscale[i]= (ob->size[i] + ob->dsize[i]) / ob->size[i];
12781                     }
12782                 }
12783             }
12784         }
12785     }
12786     /* sigh, this dscale vs dsize version patching was not done right, fix for fix,
12787      * this intentionally checks an exact subversion, also note this was never in a release,
12788      * at some point this could be removed. */
12789     else if (main->versionfile == 260 && main->subversionfile == 6)
12790     {
12791         Object *ob;
12792         for (ob= main->object.first; ob; ob= ob->id.next) {
12793             if (is_zero_v3(ob->dscale)) {
12794                 fill_vn_fl(ob->dscale, 3, 1.0f);
12795             }
12796         }
12797     }
12798 
12799     if (main->versionfile < 260 || (main->versionfile == 260 && main->subversionfile < 8))
12800     {
12801         Brush *brush;
12802 
12803         for (brush= main->brush.first; brush; brush= brush->id.next) {
12804             if (brush->sculpt_tool == SCULPT_TOOL_ROTATE)
12805                 brush->alpha= 1.0f;
12806         }
12807     }
12808 
12809     if (main->versionfile < 261 || (main->versionfile == 261 && main->subversionfile < 1))
12810     {
12811         {
12812             /* update use flags for node sockets (was only temporary before) */
12813             Scene *sce;
12814             Material *mat;
12815             Tex *tex;
12816             Lamp *lamp;
12817             World *world;
12818             bNodeTree *ntree;
12819 
12820             for (sce=main->scene.first; sce; sce=sce->id.next)
12821                 if (sce->nodetree)
12822                     do_versions_nodetree_socket_use_flags_2_62(sce->nodetree);
12823 
12824             for (mat=main->mat.first; mat; mat=mat->id.next)
12825                 if (mat->nodetree)
12826                     do_versions_nodetree_socket_use_flags_2_62(mat->nodetree);
12827 
12828             for (tex=main->tex.first; tex; tex=tex->id.next)
12829                 if (tex->nodetree)
12830                     do_versions_nodetree_socket_use_flags_2_62(tex->nodetree);
12831 
12832             for (lamp=main->lamp.first; lamp; lamp=lamp->id.next)
12833                 if (lamp->nodetree)
12834                     do_versions_nodetree_socket_use_flags_2_62(lamp->nodetree);
12835 
12836             for (world=main->world.first; world; world=world->id.next)
12837                 if (world->nodetree)
12838                     do_versions_nodetree_socket_use_flags_2_62(world->nodetree);
12839 
12840             for (ntree=main->nodetree.first; ntree; ntree=ntree->id.next)
12841                 do_versions_nodetree_socket_use_flags_2_62(ntree);
12842         }
12843         {
12844             /* Initialize BGE exit key to esc key */
12845             Scene *scene;
12846             for(scene= main->scene.first; scene; scene= scene->id.next) {
12847                 if (!scene->gm.exitkey)
12848                     scene->gm.exitkey = 218; // Blender key code for ESC
12849             }
12850         }
12851         {
12852             MovieClip *clip;
12853             Object *ob;
12854 
12855             for (clip= main->movieclip.first; clip; clip= clip->id.next) {
12856                 MovieTracking *tracking= &clip->tracking;
12857                 MovieTrackingObject *tracking_object= tracking->objects.first;
12858 
12859                 clip->proxy.build_tc_flag|= IMB_TC_RECORD_RUN_NO_GAPS;
12860 
12861                 if(!tracking->settings.object_distance)
12862                     tracking->settings.object_distance= 1.0f;
12863 
12864                 if(tracking->objects.first == NULL)
12865                     BKE_tracking_new_object(tracking, "Camera");
12866 
12867                 while(tracking_object) {
12868                     if(!tracking_object->scale)
12869                         tracking_object->scale= 1.0f;
12870 
12871                     tracking_object= tracking_object->next;
12872                 }
12873             }
12874 
12875             for (ob= main->object.first; ob; ob= ob->id.next) {
12876                 bConstraint *con;
12877                 for (con= ob->constraints.first; con; con=con->next) {
12878                     bConstraintTypeInfo *cti= constraint_get_typeinfo(con);
12879 
12880                     if(!cti)
12881                         continue;
12882 
12883                     if(cti->type==CONSTRAINT_TYPE_OBJECTSOLVER) {
12884                         bObjectSolverConstraint *data= (bObjectSolverConstraint *)con->data;
12885 
12886                         if(data->invmat[3][3]==0.0f)
12887                             unit_m4(data->invmat);
12888                     }
12889                 }
12890             }
12891         }
12892         {
12893         /* Warn the user if he is using ["Text"] properties for Font objects */
12894             Object *ob;
12895             bProperty *prop;
12896 
12897             for (ob= main->object.first; ob; ob= ob->id.next) {
12898                 if (ob->type == OB_FONT) {
12899                     prop = get_ob_property(ob, "Text");
12900                     if (prop) {
12901                         BKE_reportf_wrap(fd->reports, RPT_WARNING,
12902                                          "Game property name conflict in object: \"%s\".\nText objects reserve the "
12903                                          "[\"Text\"] game property to change their content through Logic Bricks.\n",
12904                                          ob->id.name+2);
12905                     }
12906                 }
12907             }
12908         }
12909         {
12910             /* set the SOCK_AUTO_HIDDEN flag on collapsed nodes */
12911             Scene *sce;
12912             Material *mat;
12913             Tex *tex;
12914             Lamp *lamp;
12915             World *world;
12916             bNodeTree *ntree;
12917 
12918             for (sce=main->scene.first; sce; sce=sce->id.next)
12919                 if (sce->nodetree)
12920                     do_versions_nodetree_socket_auto_hidden_flags_2_62(sce->nodetree);
12921 
12922             for (mat=main->mat.first; mat; mat=mat->id.next)
12923                 if (mat->nodetree)
12924                     do_versions_nodetree_socket_auto_hidden_flags_2_62(mat->nodetree);
12925 
12926             for (tex=main->tex.first; tex; tex=tex->id.next)
12927                 if (tex->nodetree)
12928                     do_versions_nodetree_socket_auto_hidden_flags_2_62(tex->nodetree);
12929 
12930             for (lamp=main->lamp.first; lamp; lamp=lamp->id.next)
12931                 if (lamp->nodetree)
12932                     do_versions_nodetree_socket_auto_hidden_flags_2_62(lamp->nodetree);
12933 
12934             for (world=main->world.first; world; world=world->id.next)
12935                 if (world->nodetree)
12936                     do_versions_nodetree_socket_auto_hidden_flags_2_62(world->nodetree);
12937 
12938             for (ntree=main->nodetree.first; ntree; ntree=ntree->id.next)
12939                 do_versions_nodetree_socket_auto_hidden_flags_2_62(ntree);
12940         }
12941     }
12942 
12943     if (main->versionfile < 261 || (main->versionfile == 261 && main->subversionfile < 2))
12944     {
12945         {
12946             /* convert Camera Actuator values to defines */
12947             Object *ob;
12948             bActuator *act;
12949             for(ob = main->object.first; ob; ob= ob->id.next) {
12950                 for(act= ob->actuators.first; act; act= act->next) {
12951                     if (act->type == ACT_CAMERA) {
12952                         bCameraActuator *ba= act->data;
12953 
12954                         if(ba->axis==(float) 'x') ba->axis=OB_POSX;
12955                         else if (ba->axis==(float)'y') ba->axis=OB_POSY;
12956                         /* don't do an if/else to avoid imediate subversion bump*/
12957 //                  ba->axis=((ba->axis == (float) 'x')?OB_POSX_X:OB_POSY);
12958                     }
12959                 }
12960             }
12961         }
12962 
12963         {
12964             /* convert deprecated sculpt_paint_unified_* fields to
12965                UnifiedPaintSettings */
12966             Scene *scene;
12967             for(scene= main->scene.first; scene; scene= scene->id.next) {
12968                 ToolSettings *ts= scene->toolsettings;
12969                 UnifiedPaintSettings *ups= &ts->unified_paint_settings;
12970                 ups->size= ts->sculpt_paint_unified_size;
12971                 ups->unprojected_radius= ts->sculpt_paint_unified_unprojected_radius;
12972                 ups->alpha= ts->sculpt_paint_unified_alpha;
12973                 ups->flag= ts->sculpt_paint_settings;
12974             }
12975         }
12976     }
12977 
12978     if (main->versionfile < 261 || (main->versionfile == 261 && main->subversionfile < 3))
12979     {
12980         {
12981             /* convert extended ascii to utf-8 for text editor */
12982             Text *text;
12983             for (text= main->text.first; text; text= text->id.next)
12984                 if(!(text->flags & TXT_ISEXT)) {
12985                     TextLine *tl;
12986                     
12987                     for (tl= text->lines.first; tl; tl= tl->next) {
12988                         int added= txt_extended_ascii_as_utf8(&tl->line);
12989                         tl->len+= added;
12990                         
12991                         /* reset cursor position if line was changed */
12992                         if (added && tl == text->curl)
12993                             text->curc = 0;
12994                     }
12995                 }
12996         }
12997         {
12998             /* set new dynamic paint values */
12999             Object *ob;
13000             for(ob = main->object.first; ob; ob = ob->id.next) {
13001                 ModifierData *md;
13002                 for(md= ob->modifiers.first; md; md= md->next) {
13003                     if (md->type == eModifierType_DynamicPaint) {
13004                         DynamicPaintModifierData *pmd = (DynamicPaintModifierData *)md;
13005                         if(pmd->canvas)
13006                         {
13007                             DynamicPaintSurface *surface = pmd->canvas->surfaces.first;
13008                             for (; surface; surface=surface->next) {
13009                                 surface->color_dry_threshold = 1.0f;
13010                                 surface->influence_scale = 1.0f;
13011                                 surface->radius_scale = 1.0f;
13012                                 surface->flags |= MOD_DPAINT_USE_DRYING;
13013                             }
13014                         }
13015                     }
13016                 }
13017             }
13018         }
13019     }
13020     
13021     /* put compatibility code here until next subversion bump */
13022     {
13023     }
13024 
13025     /* WATCH IT!!!: pointers from libdata have not been converted yet here! */
13026     /* WATCH IT 2!: Userdef struct init has to be in editors/interface/resources.c! */
13027 
13028     /* don't forget to set version number in blender.c! */
13029 }
13030 
13031 #if 0 // XXX: disabled for now... we still don't have this in the right place in the loading code for it to work
13032 static void do_versions_after_linking(FileData *fd, Library *lib, Main *main)
13033 {
13034     /* old Animation System (using IPO's) needs to be converted to the new Animato system */
13035     if(main->versionfile < 250)
13036         do_versions_ipos_to_animato(main);
13037 }
13038 #endif
13039 
13040 static void lib_link_all(FileData *fd, Main *main)
13041 {
13042     oldnewmap_sort(fd);
13043     
13044     lib_link_windowmanager(fd, main);
13045     lib_link_screen(fd, main);
13046     lib_link_scene(fd, main);
13047     lib_link_object(fd, main);
13048     lib_link_curve(fd, main);
13049     lib_link_mball(fd, main);
13050     lib_link_material(fd, main);
13051     lib_link_texture(fd, main);
13052     lib_link_image(fd, main);
13053     lib_link_ipo(fd, main);     // XXX depreceated... still needs to be maintained for version patches still
13054     lib_link_key(fd, main);
13055     lib_link_world(fd, main);
13056     lib_link_lamp(fd, main);
13057     lib_link_latt(fd, main);
13058     lib_link_text(fd, main);
13059     lib_link_camera(fd, main);
13060     lib_link_speaker(fd, main);
13061     lib_link_sound(fd, main);
13062     lib_link_group(fd, main);
13063     lib_link_armature(fd, main);
13064     lib_link_action(fd, main);
13065     lib_link_vfont(fd, main);
13066     lib_link_nodetree(fd, main);    /* has to be done after scene/materials, this will verify group nodes */
13067     lib_link_brush(fd, main);
13068     lib_link_particlesettings(fd, main);
13069     lib_link_movieclip(fd, main);
13070 
13071     lib_link_mesh(fd, main);        /* as last: tpage images with users at zero */
13072 
13073     lib_link_library(fd, main);     /* only init users */
13074 }
13075 
13076 static void direct_link_keymapitem(FileData *fd, wmKeyMapItem *kmi)
13077 {
13078     kmi->properties= newdataadr(fd, kmi->properties);
13079     if(kmi->properties)
13080         IDP_DirectLinkProperty(kmi->properties, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
13081     kmi->ptr= NULL;
13082     kmi->flag &= ~KMI_UPDATE;
13083 }
13084 
13085 static BHead *read_userdef(BlendFileData *bfd, FileData *fd, BHead *bhead)
13086 {
13087     UserDef *user;
13088     wmKeyMap *keymap;
13089     wmKeyMapItem *kmi;
13090     wmKeyMapDiffItem *kmdi;
13091 
13092     bfd->user= user= read_struct(fd, bhead, "user def");
13093 
13094     /* read all data into fd->datamap */
13095     bhead= read_data_into_oldnewmap(fd, bhead, "user def");
13096 
13097     if(user->keymaps.first) {
13098         /* backwards compatibility */
13099         user->user_keymaps= user->keymaps;
13100         user->keymaps.first= user->keymaps.last= NULL;
13101     }
13102 
13103     link_list(fd, &user->themes);
13104     link_list(fd, &user->user_keymaps);
13105     link_list(fd, &user->addons);
13106 
13107     for(keymap=user->user_keymaps.first; keymap; keymap=keymap->next) {
13108         keymap->modal_items= NULL;
13109         keymap->poll= NULL;
13110         keymap->flag &= ~KEYMAP_UPDATE;
13111 
13112         link_list(fd, &keymap->diff_items);
13113         link_list(fd, &keymap->items);
13114         
13115         for(kmdi=keymap->diff_items.first; kmdi; kmdi=kmdi->next) {
13116             kmdi->remove_item= newdataadr(fd, kmdi->remove_item);
13117             kmdi->add_item= newdataadr(fd, kmdi->add_item);
13118 
13119             if(kmdi->remove_item)
13120                 direct_link_keymapitem(fd, kmdi->remove_item);
13121             if(kmdi->add_item)
13122                 direct_link_keymapitem(fd, kmdi->add_item);
13123         }
13124 
13125         for(kmi=keymap->items.first; kmi; kmi=kmi->next)
13126             direct_link_keymapitem(fd, kmi);
13127     }
13128 
13129     // XXX
13130     user->uifonts.first= user->uifonts.last= NULL;
13131     
13132     link_list(fd, &user->uistyles);
13133 
13134     /* free fd->datamap again */
13135     oldnewmap_free_unused(fd->datamap);
13136     oldnewmap_clear(fd->datamap);
13137 
13138     return bhead;
13139 }
13140 
13141 BlendFileData *blo_read_file_internal(FileData *fd, const char *filepath)
13142 {
13143     BHead *bhead= blo_firstbhead(fd);
13144     BlendFileData *bfd;
13145 
13146     bfd= MEM_callocN(sizeof(BlendFileData), "blendfiledata");
13147     bfd->main= MEM_callocN(sizeof(Main), "readfile_Main");
13148     BLI_addtail(&fd->mainlist, bfd->main);
13149 
13150     bfd->main->versionfile= fd->fileversion;
13151     
13152     bfd->type= BLENFILETYPE_BLEND;
13153     BLI_strncpy(bfd->main->name, filepath, sizeof(bfd->main->name));
13154 
13155     while(bhead) {
13156         switch(bhead->code) {
13157         case DATA:
13158         case DNA1:
13159         case TEST: /* used as preview since 2.5x */
13160         case REND:
13161             bhead = blo_nextbhead(fd, bhead);
13162             break;
13163         case GLOB:
13164             bhead= read_global(bfd, fd, bhead);
13165             break;
13166         case USER:
13167             bhead= read_userdef(bfd, fd, bhead);
13168             break;
13169         case ENDB:
13170             bhead = NULL;
13171             break;
13172 
13173         case ID_LI:
13174             /* skip library datablocks in undo, this works together with
13175                BLO_read_from_memfile, where the old main->library is restored
13176                overwriting  the libraries from the memory file. previously
13177                it did not save ID_LI/ID_ID blocks in this case, but they are
13178                needed to make quit.blend recover them correctly. */
13179             if(fd->memfile)
13180                 bhead= blo_nextbhead(fd, bhead);
13181             else
13182                 bhead= read_libblock(fd, bfd->main, bhead, LIB_LOCAL, NULL);
13183             break;
13184         case ID_ID:
13185             /* same as above */
13186             if(fd->memfile)
13187                 bhead= blo_nextbhead(fd, bhead);
13188             else
13189                 /* always adds to the most recently loaded
13190                  * ID_LI block, see direct_link_library.
13191                  * this is part of the file format definition. */
13192                 bhead = read_libblock(fd, fd->mainlist.last, bhead, LIB_READ+LIB_EXTERN, NULL);
13193             break;
13194             
13195             /* in 2.50+ files, the file identifier for screens is patched, forward compatibility */
13196         case ID_SCRN:
13197             bhead->code= ID_SCR;
13198             /* deliberate pass on to default */
13199         default:
13200             bhead = read_libblock(fd, bfd->main, bhead, LIB_LOCAL, NULL);
13201         }
13202     }
13203 
13204     /* do before read_libraries, but skip undo case */
13205 //  if(fd->memfile==NULL) (the mesh shuffle hacks don't work yet? ton)
13206         do_versions(fd, NULL, bfd->main);
13207 
13208     read_libraries(fd, &fd->mainlist);
13209     
13210     blo_join_main(&fd->mainlist);
13211 
13212     lib_link_all(fd, bfd->main);
13213     //do_versions_after_linking(fd, NULL, bfd->main); // XXX: not here (or even in this function at all)! this causes crashes on many files - Aligorith (July 04, 2010)
13214     lib_verify_nodetree(bfd->main, TRUE);
13215     fix_relpaths_library(fd->relabase, bfd->main); /* make all relative paths, relative to the open blend file */
13216     
13217     link_global(fd, bfd);   /* as last */
13218     
13219     return bfd;
13220 }
13221 
13222 /* ************* APPEND LIBRARY ************** */
13223 
13224 struct bheadsort {
13225     BHead *bhead;
13226     void *old;
13227 };
13228 
13229 static int verg_bheadsort(const void *v1, const void *v2)
13230 {
13231     const struct bheadsort *x1=v1, *x2=v2;
13232     
13233     if( x1->old > x2->old) return 1;
13234     else if( x1->old < x2->old) return -1;
13235     return 0;
13236 }
13237 
13238 static void sort_bhead_old_map(FileData *fd)
13239 {
13240     BHead *bhead;
13241     struct bheadsort *bhs;
13242     int tot= 0;
13243     
13244     for (bhead= blo_firstbhead(fd); bhead; bhead= blo_nextbhead(fd, bhead))
13245         tot++;
13246     
13247     fd->tot_bheadmap= tot;
13248     if(tot==0) return;
13249     
13250     bhs= fd->bheadmap= MEM_mallocN(tot*sizeof(struct bheadsort), "bheadsort");
13251     
13252     for (bhead= blo_firstbhead(fd); bhead; bhead= blo_nextbhead(fd, bhead), bhs++) {
13253         bhs->bhead= bhead;
13254         bhs->old= bhead->old;
13255     }
13256     
13257     qsort(fd->bheadmap, tot, sizeof(struct bheadsort), verg_bheadsort);
13258         
13259 }
13260 
13261 static BHead *find_previous_lib(FileData *fd, BHead *bhead)
13262 {
13263     /* skip library datablocks in undo, see comment in read_libblock */
13264     if(fd->memfile)
13265         return NULL;
13266 
13267     for (; bhead; bhead= blo_prevbhead(fd, bhead))
13268         if (bhead->code==ID_LI)
13269             break;
13270 
13271     return bhead;
13272 }
13273 
13274 static BHead *find_bhead(FileData *fd, void *old)
13275 {
13276 #if 0
13277     BHead *bhead;
13278 #endif
13279     struct bheadsort *bhs, bhs_s;
13280     
13281     if (!old)
13282         return NULL;
13283 
13284     if (fd->bheadmap==NULL)
13285         sort_bhead_old_map(fd);
13286     
13287     bhs_s.old= old;
13288     bhs= bsearch(&bhs_s, fd->bheadmap, fd->tot_bheadmap, sizeof(struct bheadsort), verg_bheadsort);
13289 
13290     if(bhs)
13291         return bhs->bhead;
13292     
13293 #if 0
13294     for (bhead= blo_firstbhead(fd); bhead; bhead= blo_nextbhead(fd, bhead))
13295         if (bhead->old==old)
13296             return bhead;
13297 #endif
13298 
13299     return NULL;
13300 }
13301 
13302 char *bhead_id_name(FileData *fd, BHead *bhead)
13303 {
13304     return ((char *)(bhead+1)) + fd->id_name_offs;
13305 }
13306 
13307 static ID *is_yet_read(FileData *fd, Main *mainvar, BHead *bhead)
13308 {
13309     const char *idname= bhead_id_name(fd, bhead);
13310     /* which_libbase can be NULL, intentionally not using idname+2 */
13311     return BLI_findstring(which_libbase(mainvar, GS(idname)), idname, offsetof(ID, name));
13312 }
13313 
13314 static void expand_doit(FileData *fd, Main *mainvar, void *old)
13315 {
13316     BHead *bhead;
13317     ID *id;
13318 
13319     bhead= find_bhead(fd, old);
13320     if(bhead) {
13321             /* from another library? */
13322         if(bhead->code==ID_ID) {
13323             BHead *bheadlib= find_previous_lib(fd, bhead);
13324 
13325             if(bheadlib) {
13326                 Library *lib= read_struct(fd, bheadlib, "Library");
13327                 Main *ptr= blo_find_main(fd, &fd->mainlist, lib->name, fd->relabase);
13328 
13329                 id= is_yet_read(fd, ptr, bhead);
13330 
13331                 if(id==NULL) {
13332                     read_libblock(fd, ptr, bhead, LIB_READ+LIB_INDIRECT, NULL);
13333                     // commented because this can print way too much
13334                     // if(G.f & G_DEBUG) printf("expand_doit: other lib %s\n", lib->name);
13335                     
13336                     /* for outliner dependency only */
13337                     ptr->curlib->parent= mainvar->curlib;
13338                 }
13339                 else {
13340                     /* The line below was commented by Ton (I assume), when Hos did the merge from the orange branch. rev 6568
13341                      * This line is NEEDED, the case is that you have 3 blend files...
13342                      * user.blend, lib.blend and lib_indirect.blend - if user.blend already references a "tree" from
13343                      * lib_indirect.blend but lib.blend does too, linking in a Scene or Group from lib.blend can result in an
13344                      * empty without the dupli group referenced. Once you save and reload the group would appier. - Campbell */
13345                     /* This crashes files, must look further into it */
13346                     
13347                     /* Update: the issue is that in file reading, the oldnewmap is OK, but for existing data, it has to be
13348                        inserted in the map to be found! */
13349                     if(id->flag & LIB_PRE_EXISTING)
13350                         oldnewmap_insert(fd->libmap, bhead->old, id, 1);
13351                     
13352                     change_idid_adr_fd(fd, bhead->old, id);
13353                     // commented because this can print way too much
13354                     // if(G.f & G_DEBUG) printf("expand_doit: already linked: %s lib: %s\n", id->name, lib->name);
13355                 }
13356                 
13357                 MEM_freeN(lib);
13358             }
13359         }
13360         else {
13361             id= is_yet_read(fd, mainvar, bhead);
13362             if(id==NULL) {
13363                 read_libblock(fd, mainvar, bhead, LIB_TESTIND, NULL);
13364             }
13365             else {
13366                 /* this is actually only needed on UI call? when ID was already read before, and another append
13367                    happens which invokes same ID... in that case the lookup table needs this entry */
13368                 oldnewmap_insert(fd->libmap, bhead->old, id, 1);
13369                 // commented because this can print way too much
13370                 // if(G.f & G_DEBUG) printf("expand: already read %s\n", id->name);
13371             }
13372         }
13373     }
13374 }
13375 
13376 
13377 
13378 // XXX depreceated - old animation system
13379 static void expand_ipo(FileData *fd, Main *mainvar, Ipo *ipo)
13380 {
13381     IpoCurve *icu;
13382     for(icu= ipo->curve.first; icu; icu= icu->next) {
13383         if(icu->driver)
13384             expand_doit(fd, mainvar, icu->driver->ob);
13385     }
13386 }
13387 
13388 // XXX depreceated - old animation system
13389 static void expand_constraint_channels(FileData *fd, Main *mainvar, ListBase *chanbase)
13390 {
13391     bConstraintChannel *chan;
13392     for (chan=chanbase->first; chan; chan=chan->next) {
13393         expand_doit(fd, mainvar, chan->ipo);
13394     }
13395 }
13396 
13397 static void expand_fmodifiers(FileData *fd, Main *mainvar, ListBase *list)
13398 {
13399     FModifier *fcm;
13400     
13401     for (fcm= list->first; fcm; fcm= fcm->next) {
13402         /* library data for specific F-Modifier types */
13403         switch (fcm->type) {
13404             case FMODIFIER_TYPE_PYTHON:
13405             {
13406                 FMod_Python *data= (FMod_Python *)fcm->data;
13407                 
13408                 expand_doit(fd, mainvar, data->script);
13409             }
13410                 break;
13411         }
13412     }
13413 }
13414 
13415 static void expand_fcurves(FileData *fd, Main *mainvar, ListBase *list)
13416 {
13417     FCurve *fcu;
13418     
13419     for (fcu= list->first; fcu; fcu= fcu->next) {
13420         /* Driver targets if there is a driver */
13421         if (fcu->driver) {
13422             ChannelDriver *driver= fcu->driver;
13423             DriverVar *dvar;
13424             
13425             for (dvar= driver->variables.first; dvar; dvar= dvar->next) {
13426                 DRIVER_TARGETS_LOOPER(dvar) 
13427                 {
13428                     // TODO: only expand those that are going to get used?
13429                     expand_doit(fd, mainvar, dtar->id);
13430                 }
13431                 DRIVER_TARGETS_LOOPER_END
13432             }
13433         }
13434         
13435         /* F-Curve Modifiers */
13436         expand_fmodifiers(fd, mainvar, &fcu->modifiers);
13437     }
13438 }
13439 
13440 static void expand_action(FileData *fd, Main *mainvar, bAction *act)
13441 {
13442     bActionChannel *chan;
13443     
13444     // XXX depreceated - old animation system --------------
13445     for (chan=act->chanbase.first; chan; chan=chan->next) {
13446         expand_doit(fd, mainvar, chan->ipo);
13447         expand_constraint_channels(fd, mainvar, &chan->constraintChannels);
13448     }
13449     // ---------------------------------------------------
13450     
13451     /* F-Curves in Action */
13452     expand_fcurves(fd, mainvar, &act->curves);
13453 }
13454 
13455 static void expand_keyingsets(FileData *fd, Main *mainvar, ListBase *list)
13456 {
13457     KeyingSet *ks;
13458     KS_Path *ksp;
13459     
13460     /* expand the ID-pointers in KeyingSets's paths */
13461     for (ks= list->first; ks; ks= ks->next) {
13462         for (ksp= ks->paths.first; ksp; ksp= ksp->next) {
13463             expand_doit(fd, mainvar, ksp->id);
13464         }
13465     }
13466 }
13467 
13468 static void expand_animdata_nlastrips(FileData *fd, Main *mainvar, ListBase *list)
13469 {
13470     NlaStrip *strip;
13471     
13472     for (strip= list->first; strip; strip= strip->next) {
13473         /* check child strips */
13474         expand_animdata_nlastrips(fd, mainvar, &strip->strips);
13475         
13476         /* check F-Curves */
13477         expand_fcurves(fd, mainvar, &strip->fcurves);
13478         
13479         /* check F-Modifiers */
13480         expand_fmodifiers(fd, mainvar, &strip->modifiers);
13481         
13482         /* relink referenced action */
13483         expand_doit(fd, mainvar, strip->act);
13484     }
13485 }
13486 
13487 static void expand_animdata(FileData *fd, Main *mainvar, AnimData *adt)
13488 {
13489     NlaTrack *nlt;
13490     
13491     /* own action */
13492     expand_doit(fd, mainvar, adt->action);
13493     expand_doit(fd, mainvar, adt->tmpact);
13494     
13495     /* drivers - assume that these F-Curves have driver data to be in this list... */
13496     expand_fcurves(fd, mainvar, &adt->drivers);
13497     
13498     /* nla-data - referenced actions */
13499     for (nlt= adt->nla_tracks.first; nlt; nlt= nlt->next) 
13500         expand_animdata_nlastrips(fd, mainvar, &nlt->strips);
13501 }   
13502 
13503 static void expand_particlesettings(FileData *fd, Main *mainvar, ParticleSettings *part)
13504 {
13505     int a;
13506 
13507     expand_doit(fd, mainvar, part->dup_ob);
13508     expand_doit(fd, mainvar, part->dup_group);
13509     expand_doit(fd, mainvar, part->eff_group);
13510     expand_doit(fd, mainvar, part->bb_ob);
13511     
13512     if(part->adt)
13513         expand_animdata(fd, mainvar, part->adt);
13514 
13515     for(a=0; a<MAX_MTEX; a++) {
13516         if(part->mtex[a]) {
13517             expand_doit(fd, mainvar, part->mtex[a]->tex);
13518             expand_doit(fd, mainvar, part->mtex[a]->object);
13519         }
13520     }
13521 }
13522 
13523 static void expand_group(FileData *fd, Main *mainvar, Group *group)
13524 {
13525     GroupObject *go;
13526     
13527     for(go= group->gobject.first; go; go= go->next) {
13528         expand_doit(fd, mainvar, go->ob);
13529     }
13530 }
13531 
13532 static void expand_key(FileData *fd, Main *mainvar, Key *key)
13533 {
13534     expand_doit(fd, mainvar, key->ipo); // XXX depreceated - old animation system
13535     
13536     if(key->adt)
13537         expand_animdata(fd, mainvar, key->adt);
13538 }
13539 
13540 static void expand_nodetree(FileData *fd, Main *mainvar, bNodeTree *ntree)
13541 {
13542     bNode *node;
13543     
13544     if(ntree->adt)
13545         expand_animdata(fd, mainvar, ntree->adt);
13546         
13547     if(ntree->gpd)
13548         expand_doit(fd, mainvar, ntree->gpd);
13549     
13550     for(node= ntree->nodes.first; node; node= node->next)
13551         if(node->id && node->type!=CMP_NODE_R_LAYERS)
13552             expand_doit(fd, mainvar, node->id);
13553 
13554 }
13555 
13556 static void expand_texture(FileData *fd, Main *mainvar, Tex *tex)
13557 {
13558     expand_doit(fd, mainvar, tex->ima);
13559     expand_doit(fd, mainvar, tex->ipo); // XXX depreceated - old animation system
13560     
13561     if(tex->adt)
13562         expand_animdata(fd, mainvar, tex->adt);
13563     
13564     if(tex->nodetree)
13565         expand_nodetree(fd, mainvar, tex->nodetree);
13566 }
13567 
13568 static void expand_brush(FileData *fd, Main *mainvar, Brush *brush)
13569 {
13570     expand_doit(fd, mainvar, brush->mtex.tex);
13571     expand_doit(fd, mainvar, brush->clone.image);
13572 }
13573 
13574 static void expand_material(FileData *fd, Main *mainvar, Material *ma)
13575 {
13576     int a;
13577 
13578     for(a=0; a<MAX_MTEX; a++) {
13579         if(ma->mtex[a]) {
13580             expand_doit(fd, mainvar, ma->mtex[a]->tex);
13581             expand_doit(fd, mainvar, ma->mtex[a]->object);
13582         }
13583     }
13584     
13585     expand_doit(fd, mainvar, ma->ipo); // XXX depreceated - old animation system
13586     
13587     if(ma->adt)
13588         expand_animdata(fd, mainvar, ma->adt);
13589     
13590     if(ma->nodetree)
13591         expand_nodetree(fd, mainvar, ma->nodetree);
13592     
13593     if(ma->group)
13594         expand_doit(fd, mainvar, ma->group);
13595 }
13596 
13597 static void expand_lamp(FileData *fd, Main *mainvar, Lamp *la)
13598 {
13599     int a;
13600 
13601     for(a=0; a<MAX_MTEX; a++) {
13602         if(la->mtex[a]) {
13603             expand_doit(fd, mainvar, la->mtex[a]->tex);
13604             expand_doit(fd, mainvar, la->mtex[a]->object);
13605         }
13606     }
13607     
13608     expand_doit(fd, mainvar, la->ipo); // XXX depreceated - old animation system
13609     
13610     if (la->adt)
13611         expand_animdata(fd, mainvar, la->adt);
13612 
13613     if(la->nodetree)
13614         expand_nodetree(fd, mainvar, la->nodetree);
13615 }
13616 
13617 static void expand_lattice(FileData *fd, Main *mainvar, Lattice *lt)
13618 {
13619     expand_doit(fd, mainvar, lt->ipo); // XXX depreceated - old animation system
13620     expand_doit(fd, mainvar, lt->key);
13621     
13622     if (lt->adt)
13623         expand_animdata(fd, mainvar, lt->adt);
13624 }
13625 
13626 
13627 static void expand_world(FileData *fd, Main *mainvar, World *wrld)
13628 {
13629     int a;
13630 
13631     for(a=0; a<MAX_MTEX; a++) {
13632         if(wrld->mtex[a]) {
13633             expand_doit(fd, mainvar, wrld->mtex[a]->tex);
13634             expand_doit(fd, mainvar, wrld->mtex[a]->object);
13635         }
13636     }
13637     
13638     expand_doit(fd, mainvar, wrld->ipo); // XXX depreceated - old animation system
13639     
13640     if (wrld->adt)
13641         expand_animdata(fd, mainvar, wrld->adt);
13642 
13643     if(wrld->nodetree)
13644         expand_nodetree(fd, mainvar, wrld->nodetree);
13645 }
13646 
13647 
13648 static void expand_mball(FileData *fd, Main *mainvar, MetaBall *mb)
13649 {
13650     int a;
13651 
13652     for(a=0; a<mb->totcol; a++) {
13653         expand_doit(fd, mainvar, mb->mat[a]);
13654     }
13655     
13656     if(mb->adt)
13657         expand_animdata(fd, mainvar, mb->adt);
13658 }
13659 
13660 static void expand_curve(FileData *fd, Main *mainvar, Curve *cu)
13661 {
13662     int a;
13663 
13664     for(a=0; a<cu->totcol; a++) {
13665         expand_doit(fd, mainvar, cu->mat[a]);
13666     }
13667     
13668     expand_doit(fd, mainvar, cu->vfont);
13669     expand_doit(fd, mainvar, cu->vfontb);   
13670     expand_doit(fd, mainvar, cu->vfonti);
13671     expand_doit(fd, mainvar, cu->vfontbi);
13672     expand_doit(fd, mainvar, cu->key);
13673     expand_doit(fd, mainvar, cu->ipo); // XXX depreceated - old animation system
13674     expand_doit(fd, mainvar, cu->bevobj);
13675     expand_doit(fd, mainvar, cu->taperobj);
13676     expand_doit(fd, mainvar, cu->textoncurve);
13677     
13678     if(cu->adt)
13679         expand_animdata(fd, mainvar, cu->adt);
13680 }
13681 
13682 static void expand_mesh(FileData *fd, Main *mainvar, Mesh *me)
13683 {
13684     CustomDataLayer *layer;
13685     MTFace *mtf;
13686     TFace *tf;
13687     int a, i;
13688     
13689     if(me->adt)
13690         expand_animdata(fd, mainvar, me->adt);
13691         
13692     for(a=0; a<me->totcol; a++) {
13693         expand_doit(fd, mainvar, me->mat[a]);
13694     }
13695 
13696     expand_doit(fd, mainvar, me->key);
13697     expand_doit(fd, mainvar, me->texcomesh);
13698 
13699     if(me->tface) {
13700         tf= me->tface;
13701         for(i=0; i<me->totface; i++, tf++)
13702             if(tf->tpage)
13703                 expand_doit(fd, mainvar, tf->tpage);
13704     }
13705 
13706     for(a=0; a<me->fdata.totlayer; a++) {
13707         layer= &me->fdata.layers[a];
13708 
13709         if(layer->type == CD_MTFACE) {
13710             mtf= (MTFace*)layer->data;
13711             for(i=0; i<me->totface; i++, mtf++)
13712                 if(mtf->tpage)
13713                     expand_doit(fd, mainvar, mtf->tpage);
13714         }
13715     }
13716 }
13717 
13718 /* temp struct used to transport needed info to expand_constraint_cb() */
13719 typedef struct tConstraintExpandData {
13720     FileData *fd;
13721     Main *mainvar;
13722 } tConstraintExpandData;
13723 /* callback function used to expand constraint ID-links */
13724 static void expand_constraint_cb(bConstraint *UNUSED(con), ID **idpoin, void *userdata)
13725 {
13726     tConstraintExpandData *ced= (tConstraintExpandData *)userdata;
13727     expand_doit(ced->fd, ced->mainvar, *idpoin);
13728 }
13729 
13730 static void expand_constraints(FileData *fd, Main *mainvar, ListBase *lb)
13731 {
13732     tConstraintExpandData ced;
13733     bConstraint *curcon;
13734     
13735     /* relink all ID-blocks used by the constraints */
13736     ced.fd= fd;
13737     ced.mainvar= mainvar;
13738     
13739     id_loop_constraints(lb, expand_constraint_cb, &ced);
13740     
13741     /* depreceated manual expansion stuff */
13742     for (curcon=lb->first; curcon; curcon=curcon->next) {
13743         if (curcon->ipo)
13744             expand_doit(fd, mainvar, curcon->ipo); // XXX depreceated - old animation system
13745     }
13746 }
13747 
13748 static void expand_bones(FileData *fd, Main *mainvar, Bone *bone)
13749 {
13750     Bone *curBone;
13751 
13752     for (curBone = bone->childbase.first; curBone; curBone=curBone->next) {
13753         expand_bones(fd, mainvar, curBone);
13754     }
13755 
13756 }
13757 
13758 static void expand_pose(FileData *fd, Main *mainvar, bPose *pose)
13759 {
13760     bPoseChannel *chan;
13761 
13762     if (!pose)
13763         return;
13764 
13765     for (chan = pose->chanbase.first; chan; chan=chan->next) {
13766         expand_constraints(fd, mainvar, &chan->constraints);
13767         expand_doit(fd, mainvar, chan->custom);
13768     }
13769 }
13770 
13771 static void expand_armature(FileData *fd, Main *mainvar, bArmature *arm)
13772 {
13773     Bone *curBone;
13774 
13775     if(arm->adt)
13776         expand_animdata(fd, mainvar, arm->adt);
13777 
13778     for (curBone = arm->bonebase.first; curBone; curBone=curBone->next) {
13779         expand_bones(fd, mainvar, curBone);
13780     }
13781 }
13782 
13783 static void expand_object_expandModifiers(void *userData, Object *UNUSED(ob),
13784                                               ID **idpoin)
13785 {
13786     struct { FileData *fd; Main *mainvar; } *data= userData;
13787 
13788     FileData *fd= data->fd;
13789     Main *mainvar= data->mainvar;
13790 
13791     expand_doit(fd, mainvar, *idpoin);
13792 }
13793 
13794 static void expand_object(FileData *fd, Main *mainvar, Object *ob)
13795 {
13796     ParticleSystem *psys;
13797     bSensor *sens;
13798     bController *cont;
13799     bActuator *act;
13800     bActionStrip *strip;
13801     PartEff *paf;
13802     int a;
13803 
13804     expand_doit(fd, mainvar, ob->data);
13805 
13806     /* expand_object_expandModifier() */
13807     if(ob->modifiers.first) {
13808         struct { FileData *fd; Main *mainvar; } data;
13809         data.fd= fd;
13810         data.mainvar= mainvar;
13811 
13812         modifiers_foreachIDLink(ob, expand_object_expandModifiers, (void *)&data);
13813     }
13814 
13815     expand_pose(fd, mainvar, ob->pose);
13816     expand_doit(fd, mainvar, ob->poselib);
13817     expand_constraints(fd, mainvar, &ob->constraints);
13818     
13819     expand_doit(fd, mainvar, ob->gpd);
13820     
13821 // XXX depreceated - old animation system (for version patching only) 
13822     expand_doit(fd, mainvar, ob->ipo);
13823     expand_doit(fd, mainvar, ob->action);
13824     
13825     expand_constraint_channels(fd, mainvar, &ob->constraintChannels);
13826 
13827     for (strip=ob->nlastrips.first; strip; strip=strip->next){
13828         expand_doit(fd, mainvar, strip->object);
13829         expand_doit(fd, mainvar, strip->act);
13830         expand_doit(fd, mainvar, strip->ipo);
13831     }
13832 // XXX depreceated - old animation system (for version patching only)
13833     
13834     if(ob->adt)
13835         expand_animdata(fd, mainvar, ob->adt);
13836     
13837     for(a=0; a<ob->totcol; a++) {
13838         expand_doit(fd, mainvar, ob->mat[a]);
13839     }
13840     
13841     paf = do_version_give_parteff_245(ob);
13842     if (paf && paf->group) 
13843         expand_doit(fd, mainvar, paf->group);
13844 
13845     if(ob->dup_group)
13846         expand_doit(fd, mainvar, ob->dup_group);
13847     
13848     if(ob->proxy)
13849         expand_doit(fd, mainvar, ob->proxy);
13850     if(ob->proxy_group)
13851         expand_doit(fd, mainvar, ob->proxy_group);
13852 
13853     for(psys=ob->particlesystem.first; psys; psys=psys->next)
13854         expand_doit(fd, mainvar, psys->part);
13855 
13856     sens= ob->sensors.first;
13857     while(sens) {
13858         if(sens->type==SENS_TOUCH) {
13859             bTouchSensor *ts= sens->data;
13860             expand_doit(fd, mainvar, ts->ma);
13861         }
13862         else if(sens->type==SENS_MESSAGE) {
13863             bMessageSensor *ms= sens->data;
13864             expand_doit(fd, mainvar, ms->fromObject);
13865         }
13866         sens= sens->next;
13867     }
13868 
13869     cont= ob->controllers.first;
13870     while(cont) {
13871         if(cont->type==CONT_PYTHON) {
13872             bPythonCont *pc= cont->data;
13873             expand_doit(fd, mainvar, pc->text);
13874         }
13875         cont= cont->next;
13876     }
13877 
13878     act= ob->actuators.first;
13879     while(act) {
13880         if(act->type==ACT_SOUND) {
13881             bSoundActuator *sa= act->data;
13882             expand_doit(fd, mainvar, sa->sound);
13883         }
13884         else if(act->type==ACT_CAMERA) {
13885             bCameraActuator *ca= act->data;
13886             expand_doit(fd, mainvar, ca->ob);
13887         }
13888         else if(act->type==ACT_EDIT_OBJECT) {
13889             bEditObjectActuator *eoa= act->data;
13890             if(eoa) {
13891                 expand_doit(fd, mainvar, eoa->ob);
13892                 expand_doit(fd, mainvar, eoa->me);
13893             }
13894         }
13895         else if(act->type==ACT_OBJECT) {
13896             bObjectActuator *oa= act->data;
13897             expand_doit(fd, mainvar, oa->reference);
13898         }
13899         else if(act->type==ACT_ADD_OBJECT) {
13900             bAddObjectActuator *aoa= act->data;
13901             expand_doit(fd, mainvar, aoa->ob);
13902         }
13903         else if(act->type==ACT_SCENE) {
13904             bSceneActuator *sa= act->data;
13905             expand_doit(fd, mainvar, sa->camera);
13906             expand_doit(fd, mainvar, sa->scene);
13907         }
13908         else if(act->type==ACT_2DFILTER) {
13909             bTwoDFilterActuator *tdfa= act->data;
13910             expand_doit(fd, mainvar, tdfa->text);
13911         }
13912         else if(act->type==ACT_ACTION) {
13913             bActionActuator *aa= act->data;
13914             expand_doit(fd, mainvar, aa->act);
13915         }
13916         else if(act->type==ACT_SHAPEACTION) {
13917             bActionActuator *aa= act->data;
13918             expand_doit(fd, mainvar, aa->act);
13919         }
13920         else if(act->type==ACT_PROPERTY) {
13921             bPropertyActuator *pa= act->data;
13922             expand_doit(fd, mainvar, pa->ob);
13923         }
13924         else if(act->type==ACT_MESSAGE) {
13925             bMessageActuator *ma= act->data;
13926             expand_doit(fd, mainvar, ma->toObject);
13927         }
13928         else if(act->type==ACT_PARENT) {
13929             bParentActuator *pa= act->data;
13930             expand_doit(fd, mainvar, pa->ob);
13931         }
13932         else if(act->type==ACT_ARMATURE) {
13933             bArmatureActuator *arma= act->data;
13934             expand_doit(fd, mainvar, arma->target);
13935         }
13936         else if(act->type==ACT_STEERING) {
13937             bSteeringActuator *sta= act->data;
13938             expand_doit(fd, mainvar, sta->target);
13939             expand_doit(fd, mainvar, sta->navmesh);
13940         }
13941         act= act->next;
13942     }
13943 
13944     if(ob->pd && ob->pd->tex)
13945         expand_doit(fd, mainvar, ob->pd->tex);
13946     
13947 }
13948 
13949 static void expand_scene(FileData *fd, Main *mainvar, Scene *sce)
13950 {
13951     Base *base;
13952     SceneRenderLayer *srl;
13953 
13954     for(base= sce->base.first; base; base= base->next) {
13955         expand_doit(fd, mainvar, base->object);
13956     }
13957     expand_doit(fd, mainvar, sce->camera);
13958     expand_doit(fd, mainvar, sce->world);
13959     
13960     if(sce->adt)
13961         expand_animdata(fd, mainvar, sce->adt);
13962     expand_keyingsets(fd, mainvar, &sce->keyingsets);
13963     
13964     if(sce->set)
13965         expand_doit(fd, mainvar, sce->set);
13966     
13967     if(sce->nodetree)
13968         expand_nodetree(fd, mainvar, sce->nodetree);
13969     
13970     for(srl= sce->r.layers.first; srl; srl= srl->next) {
13971         expand_doit(fd, mainvar, srl->mat_override);
13972         expand_doit(fd, mainvar, srl->light_override);
13973     }
13974 
13975     if(sce->r.dometext)
13976         expand_doit(fd, mainvar, sce->gm.dome.warptext);
13977         
13978     if(sce->gpd)
13979         expand_doit(fd, mainvar, sce->gpd);
13980 
13981     if(sce->ed) {
13982         Sequence *seq;
13983 
13984         SEQ_BEGIN(sce->ed, seq) {
13985             if(seq->scene) expand_doit(fd, mainvar, seq->scene);
13986             if(seq->scene_camera) expand_doit(fd, mainvar, seq->scene_camera);
13987             if(seq->sound) expand_doit(fd, mainvar, seq->sound);
13988         }
13989         SEQ_END
13990     }
13991 
13992 #ifdef DURIAN_CAMERA_SWITCH
13993     {
13994         TimeMarker *marker;
13995 
13996         for(marker= sce->markers.first; marker; marker= marker->next) {
13997             if(marker->camera) {
13998                 expand_doit(fd, mainvar, marker->camera);
13999             }
14000         }
14001     }
14002 #endif
14003 }
14004 
14005 static void expand_camera(FileData *fd, Main *mainvar, Camera *ca)
14006 {
14007     expand_doit(fd, mainvar, ca->ipo); // XXX depreceated - old animation system
14008     
14009     if(ca->adt)
14010         expand_animdata(fd, mainvar, ca->adt);
14011 }
14012 
14013 static void expand_speaker(FileData *fd, Main *mainvar, Speaker *spk)
14014 {
14015     expand_doit(fd, mainvar, spk->sound);
14016 
14017     if (spk->adt)
14018         expand_animdata(fd, mainvar, spk->adt);
14019 }
14020 
14021 static void expand_sound(FileData *fd, Main *mainvar, bSound *snd)
14022 {
14023     expand_doit(fd, mainvar, snd->ipo); // XXX depreceated - old animation system
14024 }
14025 
14026 
14027 static void expand_main(FileData *fd, Main *mainvar)
14028 {
14029     ListBase *lbarray[MAX_LIBARRAY];
14030     ID *id;
14031     int a, doit= 1;
14032 
14033     if(fd==NULL) return;
14034 
14035     while(doit) {
14036         doit= 0;
14037 
14038         a= set_listbasepointers(mainvar, lbarray);
14039         while(a--) {
14040             id= lbarray[a]->first;
14041 
14042             while(id) {
14043                 if(id->flag & LIB_TEST) {
14044 
14045                     switch(GS(id->name)) {
14046 
14047                     case ID_OB:
14048                         expand_object(fd, mainvar, (Object *)id);
14049                         break;
14050                     case ID_ME:
14051                         expand_mesh(fd, mainvar, (Mesh *)id);
14052                         break;
14053                     case ID_CU:
14054                         expand_curve(fd, mainvar, (Curve *)id);
14055                         break;
14056                     case ID_MB:
14057                         expand_mball(fd, mainvar, (MetaBall *)id);
14058                         break;
14059                     case ID_SCE:
14060                         expand_scene(fd, mainvar, (Scene *)id);
14061                         break;
14062                     case ID_MA:
14063                         expand_material(fd, mainvar, (Material *)id);
14064                         break;
14065                     case ID_TE:
14066                         expand_texture(fd, mainvar, (Tex *)id);
14067                         break;
14068                     case ID_WO:
14069                         expand_world(fd, mainvar, (World *)id);
14070                         break;
14071                     case ID_LT:
14072                         expand_lattice(fd, mainvar, (Lattice *)id);
14073                         break;
14074                     case ID_LA:
14075                         expand_lamp(fd, mainvar,(Lamp *)id);
14076                         break;
14077                     case ID_KE:
14078                         expand_key(fd, mainvar, (Key *)id);
14079                         break;
14080                     case ID_CA:
14081                         expand_camera(fd, mainvar, (Camera *)id);
14082                         break;
14083                     case ID_SPK:
14084                         expand_speaker(fd, mainvar,(Speaker *)id);
14085                         break;
14086                     case ID_SO:
14087                         expand_sound(fd, mainvar, (bSound *)id);
14088                         break;
14089                     case ID_AR:
14090                         expand_armature(fd, mainvar, (bArmature *)id);
14091                         break;
14092                     case ID_AC:
14093                         expand_action(fd, mainvar, (bAction *)id); // XXX depreceated - old animation system
14094                         break;
14095                     case ID_GR:
14096                         expand_group(fd, mainvar, (Group *)id);
14097                         break;
14098                     case ID_NT:
14099                         expand_nodetree(fd, mainvar, (bNodeTree *)id);
14100                         break;
14101                     case ID_BR:
14102                         expand_brush(fd, mainvar, (Brush *)id);
14103                         break;
14104                     case ID_IP:
14105                         expand_ipo(fd, mainvar, (Ipo *)id); // XXX depreceated - old animation system
14106                         break;
14107                     case ID_PA:
14108                         expand_particlesettings(fd, mainvar, (ParticleSettings *)id);
14109                     }
14110 
14111                     doit= 1;
14112                     id->flag -= LIB_TEST;
14113 
14114                 }
14115                 id= id->next;
14116             }
14117         }
14118     }
14119 }
14120 
14121 static int object_in_any_scene(Main *mainvar, Object *ob)
14122 {
14123     Scene *sce;
14124     
14125     for(sce= mainvar->scene.first; sce; sce= sce->id.next)
14126         if(object_in_scene(ob, sce))
14127             return 1;
14128     return 0;
14129 }
14130 
14131 static void give_base_to_objects(Main *mainvar, Scene *sce, Library *lib, const short idcode, const short is_link)
14132 {
14133     Object *ob;
14134     Base *base;
14135     const short is_group_append= (is_link==FALSE && idcode==ID_GR);
14136 
14137     /* give all objects which are LIB_INDIRECT a base, or for a group when *lib has been set */
14138     for(ob= mainvar->object.first; ob; ob= ob->id.next) {
14139         
14140         if( ob->id.flag & LIB_INDIRECT ) {
14141             
14142                 /* IF below is quite confusing!
14143                 if we are appending, but this object wasnt just added along with a group,
14144                 then this is already used indirectly in the scene somewhere else and we didnt just append it.
14145                 
14146                 (ob->id.flag & LIB_PRE_EXISTING)==0 means that this is a newly appended object - Campbell */
14147             if (is_group_append==0 || (ob->id.flag & LIB_PRE_EXISTING)==0) {
14148                 
14149                 int do_it= 0;
14150                 
14151                 if(ob->id.us==0) {
14152                     do_it= 1;
14153                 }
14154                 else if(idcode==ID_GR) {
14155                     if(ob->id.us==1 && is_link==FALSE && ob->id.lib==lib) {
14156                         if((ob->flag & OB_FROMGROUP) && object_in_any_scene(mainvar, ob)==0) {
14157                             do_it= 1;
14158                         }
14159                     }
14160                 }
14161                 else {
14162                     /* when appending, make sure any indirectly loaded objects
14163                      * get a base else they cant be accessed at all [#27437] */
14164                     if(ob->id.us==1 && is_link==FALSE && ob->id.lib==lib) {
14165 
14166                         /* we may be appending from a scene where we already
14167                          *  have a linked object which is not in any scene [#27616] */
14168                         if((ob->id.flag & LIB_PRE_EXISTING)==0) {
14169 
14170                             if(object_in_any_scene(mainvar, ob)==0) {
14171                                 do_it= 1;
14172                             }
14173                         }
14174                     }
14175                 }
14176 
14177                 if(do_it) {
14178                     base= MEM_callocN( sizeof(Base), "add_ext_base");
14179                     BLI_addtail(&(sce->base), base);
14180                     base->lay= ob->lay;
14181                     base->object= ob;
14182                     base->flag= ob->flag;
14183                     ob->id.us= 1;
14184                     
14185                     ob->id.flag -= LIB_INDIRECT;
14186                     ob->id.flag |= LIB_EXTERN;
14187                 }
14188             }
14189         }
14190     }
14191 }
14192 
14193 static void give_base_to_groups(Main *mainvar, Scene *scene)
14194 {
14195     Group *group;
14196 
14197     /* give all objects which are LIB_INDIRECT a base, or for a group when *lib has been set */
14198     for(group= mainvar->group.first; group; group= group->id.next) {
14199         if(((group->id.flag & LIB_INDIRECT)==0 && (group->id.flag & LIB_PRE_EXISTING)==0)) {
14200             Base *base;
14201 
14202             /* add_object(...) messes with the selection */
14203             Object *ob= add_only_object(OB_EMPTY, group->id.name+2);
14204             ob->type= OB_EMPTY;
14205             ob->lay= scene->lay;
14206 
14207             /* assign the base */
14208             base= scene_add_base(scene, ob);
14209             base->flag |= SELECT;
14210             base->object->flag= base->flag;
14211             ob->recalc |= OB_RECALC_OB|OB_RECALC_DATA|OB_RECALC_TIME;
14212             scene->basact= base;
14213 
14214             /* assign the group */
14215             ob->dup_group= group;
14216             ob->transflag |= OB_DUPLIGROUP;
14217             rename_id(&ob->id, group->id.name+2);
14218             copy_v3_v3(ob->loc, scene->cursor);
14219         }
14220     }
14221 }
14222 
14223 /* returns true if the item was found
14224 * but it may already have already been appended/linked */
14225 static ID *append_named_part(Main *mainl, FileData *fd, const char *idname, const short idcode)
14226 {
14227     BHead *bhead;
14228     ID *id= NULL;
14229     int found=0;
14230 
14231     for(bhead= blo_firstbhead(fd); bhead; bhead= blo_nextbhead(fd, bhead)) {
14232         if(bhead->code==idcode) {
14233             const char *idname_test= bhead_id_name(fd, bhead);
14234 
14235             if(strcmp(idname_test + 2, idname)==0) {
14236                 found= 1;
14237                 id= is_yet_read(fd, mainl, bhead);
14238                 if(id==NULL) {
14239                     read_libblock(fd, mainl, bhead, LIB_TESTEXT, &id);
14240                 }
14241                 else {
14242                     printf("append: already linked\n");
14243                     oldnewmap_insert(fd->libmap, bhead->old, id, 1);
14244                     if(id->flag & LIB_INDIRECT) {
14245                         id->flag -= LIB_INDIRECT;
14246                         id->flag |= LIB_EXTERN;
14247                     }
14248                 }
14249 
14250                 break;
14251             }
14252         }
14253         else if(bhead->code==ENDB) {
14254             break;
14255         }
14256     }
14257 
14258     /* if we found the id but the id is NULL, this is really bad */
14259     BLI_assert((found != 0) == (id != NULL));
14260 
14261     return found ? id : NULL;
14262 }
14263 
14264 static ID *append_named_part_ex(const bContext *C, Main *mainl, FileData *fd, const char *idname, const int idcode, const int flag)
14265 {
14266     ID *id= append_named_part(mainl, fd, idname, idcode);
14267 
14268     if(id && (GS(id->name) == ID_OB)) { /* loose object: give a base */
14269         Scene *scene= CTX_data_scene(C); /* can be NULL */
14270         if(scene) {
14271             Base *base;
14272             Object *ob;
14273 
14274             base= MEM_callocN( sizeof(Base), "app_nam_part");
14275             BLI_addtail(&scene->base, base);
14276 
14277             ob= (Object *)id;
14278 
14279             /* link at active layer (view3d->lay if in context, else scene->lay */
14280             if((flag & FILE_ACTIVELAY)) {
14281                 View3D *v3d = CTX_wm_view3d(C);
14282                 ob->lay = v3d ? v3d->layact : scene->lay;
14283             }
14284 
14285             ob->mode= 0;
14286             base->lay= ob->lay;
14287             base->object= ob;
14288             ob->id.us++;
14289 
14290             if(flag & FILE_AUTOSELECT) {
14291                 base->flag |= SELECT;
14292                 base->object->flag = base->flag;
14293                 /* do NOT make base active here! screws up GUI stuff, if you want it do it on src/ level */
14294             }
14295         }
14296     }
14297 
14298     return id;
14299 }
14300 
14301 ID *BLO_library_append_named_part(Main *mainl, BlendHandle** bh, const char *idname, const int idcode)
14302 {
14303     FileData *fd= (FileData*)(*bh);
14304     return append_named_part(mainl, fd, idname, idcode);
14305 }
14306 
14307 ID *BLO_library_append_named_part_ex(const bContext *C, Main *mainl, BlendHandle** bh, const char *idname, const int idcode, const short flag)
14308 {
14309     FileData *fd= (FileData*)(*bh);
14310     return append_named_part_ex(C, mainl, fd, idname, idcode, flag);
14311 }
14312 
14313 static void append_id_part(FileData *fd, Main *mainvar, ID *id, ID **id_r)
14314 {
14315     BHead *bhead;
14316 
14317     for (bhead= blo_firstbhead(fd); bhead; bhead= blo_nextbhead(fd, bhead)) {
14318         if (bhead->code == GS(id->name)) {
14319 
14320             if (strcmp(id->name, bhead_id_name(fd, bhead))==0) {
14321                 id->flag &= ~LIB_READ;
14322                 id->flag |= LIB_TEST;
14323 //              printf("read lib block %s\n", id->name);
14324                 read_libblock(fd, mainvar, bhead, id->flag, id_r);
14325 
14326                 break;
14327             }
14328         } else if (bhead->code==ENDB)
14329             break;
14330     }
14331 }
14332 
14333 /* common routine to append/link something from a library */
14334 
14335 static Main* library_append_begin(Main *mainvar, FileData **fd, const char *filepath)
14336 {
14337     Main *mainl;
14338 
14339     /* make mains */
14340     blo_split_main(&(*fd)->mainlist, mainvar);
14341 
14342     /* which one do we need? */
14343     mainl = blo_find_main(*fd, &(*fd)->mainlist, filepath, G.main->name);
14344     
14345     /* needed for do_version */
14346     mainl->versionfile= (*fd)->fileversion;
14347     read_file_version(*fd, mainl);
14348     
14349     return mainl;
14350 }
14351 
14352 Main* BLO_library_append_begin(Main *mainvar, BlendHandle** bh, const char *filepath)
14353 {
14354     FileData *fd= (FileData*)(*bh);
14355     return library_append_begin(mainvar, &fd, filepath);
14356 }
14357 
14358 
14359 /* Context == NULL signifies not to do any scene manipulation */
14360 static void library_append_end(const bContext *C, Main *mainl, FileData **fd, int idcode, short flag)
14361 {
14362     Main *mainvar;
14363     Library *curlib;
14364 
14365     /* make main consistent */
14366     expand_main(*fd, mainl);
14367 
14368     /* do this when expand found other libs */
14369     read_libraries(*fd, &(*fd)->mainlist);
14370     
14371     curlib= mainl->curlib;
14372 
14373     /* make the lib path relative if required */
14374     if(flag & FILE_RELPATH) {
14375 
14376         /* use the full path, this could have been read by other library even */
14377         BLI_strncpy(curlib->name, curlib->filepath, sizeof(curlib->name));
14378         
14379         /* uses current .blend file as reference */
14380         BLI_path_rel(curlib->name, G.main->name);
14381     }
14382 
14383     blo_join_main(&(*fd)->mainlist);
14384     mainvar= (*fd)->mainlist.first;
14385     mainl= NULL; /* blo_join_main free's mainl, cant use anymore */
14386 
14387     lib_link_all(*fd, mainvar);
14388     lib_verify_nodetree(mainvar, FALSE);
14389     fix_relpaths_library(G.main->name, mainvar); /* make all relative paths, relative to the open blend file */
14390 
14391     if(C) {
14392         Scene *scene= CTX_data_scene(C);
14393 
14394         /* give a base to loose objects. If group append, do it for objects too */
14395         if(scene) {
14396             const short is_link= (flag & FILE_LINK) != 0;
14397             if(idcode==ID_SCE) {
14398                 /* dont instance anything when linking in scenes, assume the scene its self instances the data */
14399             }
14400             else {
14401                 give_base_to_objects(mainvar, scene, curlib, idcode, is_link);
14402 
14403                 if (flag & FILE_GROUP_INSTANCE) {
14404                     give_base_to_groups(mainvar, scene);
14405                 }
14406             }
14407         }
14408         else {
14409             printf("library_append_end, scene is NULL (objects wont get bases)\n");
14410         }
14411     }
14412     /* has been removed... erm, why? s..ton) */
14413     /* 20040907: looks like they are give base already in append_named_part(); -Nathan L */
14414     /* 20041208: put back. It only linked direct, not indirect objects (ton) */
14415     
14416     /* patch to prevent switch_endian happens twice */
14417     if((*fd)->flags & FD_FLAGS_SWITCH_ENDIAN) {
14418         blo_freefiledata( *fd );
14419         *fd = NULL;
14420     }   
14421 }
14422 
14423 void BLO_library_append_end(const bContext *C, struct Main *mainl, BlendHandle** bh, int idcode, short flag)
14424 {
14425     FileData *fd= (FileData*)(*bh);
14426     library_append_end(C, mainl, &fd, idcode, flag);
14427     *bh= (BlendHandle*)fd;
14428 }
14429 
14430 void *BLO_library_read_struct(FileData *fd, BHead *bh, const char *blockname)
14431 {
14432     return read_struct(fd, bh, blockname);
14433 }
14434 
14435 /* ************* READ LIBRARY ************** */
14436 
14437 static int mainvar_count_libread_blocks(Main *mainvar)
14438 {
14439     ListBase *lbarray[MAX_LIBARRAY];
14440     int a, tot= 0;
14441 
14442     a= set_listbasepointers(mainvar, lbarray);
14443     while(a--) {
14444         ID *id;
14445 
14446         for (id= lbarray[a]->first; id; id= id->next)
14447             if (id->flag & LIB_READ)
14448                 tot++;
14449     }
14450     return tot;
14451 }
14452 
14453 static void read_libraries(FileData *basefd, ListBase *mainlist)
14454 {
14455     Main *mainl= mainlist->first;
14456     Main *mainptr;
14457     ListBase *lbarray[MAX_LIBARRAY];
14458     int a, doit= 1;
14459 
14460     while(doit) {
14461         doit= 0;
14462 
14463         /* test 1: read libdata */
14464         mainptr= mainl->next;
14465         while(mainptr) {
14466             int tot= mainvar_count_libread_blocks(mainptr);
14467             
14468             // printf("found LIB_READ %s\n", mainptr->curlib->name);
14469             if(tot) {
14470                 FileData *fd= mainptr->curlib->filedata;
14471 
14472                 if(fd==NULL) {
14473 
14474                     /* printf and reports for now... its important users know this */
14475                     BKE_reportf_wrap(basefd->reports, RPT_INFO,
14476                                      "read library:  '%s', '%s'\n",
14477                                      mainptr->curlib->filepath, mainptr->curlib->name);
14478 
14479                     fd= blo_openblenderfile(mainptr->curlib->filepath, basefd->reports);
14480                     
14481                     /* allow typing in a new lib path */
14482                     if(G.rt==-666) {
14483                         while(fd==NULL) {
14484                             char newlib_path[FILE_MAX] = { 0 };
14485                             printf("Missing library...'\n");
14486                             printf("    current file: %s\n", G.main->name);
14487                             printf("    absolute lib: %s\n", mainptr->curlib->filepath);
14488                             printf("    relative lib: %s\n", mainptr->curlib->name);
14489                             printf("  enter a new path:\n");
14490 
14491                             if(scanf("%s", newlib_path) > 0) {
14492                                 BLI_strncpy(mainptr->curlib->name, newlib_path, sizeof(mainptr->curlib->name));
14493                                 BLI_strncpy(mainptr->curlib->filepath, newlib_path, sizeof(mainptr->curlib->filepath));
14494                                 cleanup_path(G.main->name, mainptr->curlib->filepath);
14495                                 
14496                                 fd= blo_openblenderfile(mainptr->curlib->filepath, basefd->reports);
14497 
14498                                 if(fd) {
14499                                     printf("found: '%s', party on macuno!\n", mainptr->curlib->filepath);
14500                                 }
14501                             }
14502                         }
14503                     }
14504 
14505                     if (fd) {
14506                         fd->reports= basefd->reports;
14507                         
14508                         if (fd->libmap)
14509                             oldnewmap_free(fd->libmap);
14510 
14511                         fd->libmap = oldnewmap_new();
14512                         
14513                         mainptr->curlib->filedata= fd;
14514                         mainptr->versionfile= fd->fileversion;
14515                         
14516                         /* subversion */
14517                         read_file_version(fd, mainptr);
14518                     }
14519                     else mainptr->curlib->filedata= NULL;
14520 
14521                     if (fd==NULL) {
14522                         BKE_reportf_wrap(basefd->reports, RPT_ERROR,
14523                                          "Can't find lib '%s'\n",
14524                                          mainptr->curlib->filepath);
14525                     }
14526                 }
14527                 if(fd) {
14528                     doit= 1;
14529                     a= set_listbasepointers(mainptr, lbarray);
14530                     while(a--) {
14531                         ID *id= lbarray[a]->first;
14532 
14533                         while(id) {
14534                             ID *idn= id->next;
14535                             if(id->flag & LIB_READ) {
14536                                 ID *realid= NULL;
14537                                 BLI_remlink(lbarray[a], id);
14538 
14539                                 append_id_part(fd, mainptr, id, &realid);
14540                                 if (!realid) {
14541                                     BKE_reportf_wrap(fd->reports, RPT_ERROR,
14542                                                      "LIB ERROR: %s:'%s' missing from '%s'\n",
14543                                                      BKE_idcode_to_name(GS(id->name)),
14544                                                      id->name+2, mainptr->curlib->filepath);
14545                                 }
14546                                 
14547                                 change_idid_adr(mainlist, basefd, id, realid);
14548 
14549                                 MEM_freeN(id);
14550                             }
14551                             id= idn;
14552                         }
14553                     }
14554 
14555                     expand_main(fd, mainptr);
14556                     
14557                     /* dang FileData... now new libraries need to be appended to original filedata,
14558                      * it is not a good replacement for the old global (ton) */
14559                     while( fd->mainlist.first ) {
14560                         Main *mp= fd->mainlist.first;
14561                         BLI_remlink(&fd->mainlist, mp);
14562                         BLI_addtail(&basefd->mainlist, mp);
14563                     }
14564                 }
14565             }
14566 
14567             mainptr= mainptr->next;
14568         }
14569     }
14570     
14571     /* test if there are unread libblocks */
14572     for(mainptr= mainl->next; mainptr; mainptr= mainptr->next) {
14573         a= set_listbasepointers(mainptr, lbarray);
14574         while(a--) {
14575             ID *id= lbarray[a]->first;
14576             while(id) {
14577                 ID *idn= id->next;
14578                 if(id->flag & LIB_READ) {
14579                     BLI_remlink(lbarray[a], id);
14580                     BKE_reportf_wrap(basefd->reports, RPT_ERROR,
14581                                      "LIB ERROR: %s:'%s' unread libblock missing from '%s'\n",
14582                                      BKE_idcode_to_name(GS(id->name)), id->name+2, mainptr->curlib->filepath);
14583                     change_idid_adr(mainlist, basefd, id, NULL);
14584 
14585                     MEM_freeN(id);
14586                 }
14587                 id= idn;
14588             }
14589         }
14590     }
14591     
14592     /* do versions, link, and free */
14593     for(mainptr= mainl->next; mainptr; mainptr= mainptr->next) {
14594         /* some mains still have to be read, then
14595          * versionfile is still zero! */
14596         if(mainptr->versionfile) {
14597             if(mainptr->curlib->filedata) // can be zero... with shift+f1 append
14598                 do_versions(mainptr->curlib->filedata, mainptr->curlib, mainptr);
14599             else
14600                 do_versions(basefd, NULL, mainptr);
14601         }
14602         
14603         if(mainptr->curlib->filedata)
14604             lib_link_all(mainptr->curlib->filedata, mainptr);
14605         
14606         if(mainptr->curlib->filedata) blo_freefiledata(mainptr->curlib->filedata);
14607         mainptr->curlib->filedata= NULL;
14608     }
14609 }
14610 
14611 
14612 /* reading runtime */
14613 
14614 BlendFileData *blo_read_blendafterruntime(int file, const char *name, int actualsize, ReportList *reports)
14615 {
14616     BlendFileData *bfd = NULL;
14617     FileData *fd = filedata_new();
14618     fd->filedes = file;
14619     fd->buffersize = actualsize;
14620     fd->read = fd_read_from_file;
14621 
14622     /* needed for library_append and read_libraries */
14623     BLI_strncpy(fd->relabase, name, sizeof(fd->relabase));
14624 
14625     fd = blo_decode_and_check(fd, reports);
14626     if (!fd)
14627         return NULL;
14628 
14629     fd->reports= reports;
14630     bfd= blo_read_file_internal(fd, "");
14631     blo_freefiledata(fd);
14632 
14633     return bfd;
14634 }