soc-2008-mxcurioni: merged changes to revision 15441
[blender.git] / source / creator / creator.c
1 /*
2  * $Id$
3  *
4  * ***** BEGIN GPL LICENSE BLOCK *****
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19  *
20  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
21  * All rights reserved.
22  *
23  * The Original Code is: all of this file.
24  *
25  * Contributor(s): none yet.
26  *
27  * ***** END GPL LICENSE BLOCK *****
28  */
29 #include <stdlib.h>
30 #include <string.h>
31
32 /* This little block needed for linking to Blender... */
33
34 #include "MEM_guardedalloc.h"
35
36 #ifdef WIN32
37 #include "BLI_winstuff.h"
38 #endif
39
40 #include "GEN_messaging.h"
41
42 #include "DNA_ID.h"
43 #include "DNA_scene_types.h"
44
45 #include "BLI_blenlib.h"
46 #include "blendef.h" /* for MAXFRAME */
47
48
49 #include "BKE_utildefines.h"
50 #include "BKE_blender.h"
51 #include "BKE_font.h"
52 #include "BKE_global.h"
53 #include "BKE_main.h"
54 #include "BKE_material.h"
55 #include "BKE_packedFile.h"
56 #include "BKE_scene.h"
57 #include "BKE_node.h"
58
59 #include "BIF_gl.h"
60 #include "BIF_graphics.h"
61 #include "BIF_mainqueue.h"
62 #include "BIF_graphics.h"
63 #include "BIF_editsound.h"
64 #include "BIF_usiblender.h"
65 #include "BIF_drawscene.h"      /* set_scene() */
66 #include "BIF_screen.h"         /* waitcursor and more */
67 #include "BIF_usiblender.h"
68 #include "BIF_toolbox.h"
69
70 #include "BLO_writefile.h"
71 #include "BLO_readfile.h"
72
73 #include "BDR_drawmesh.h"
74
75 #include "IMB_imbuf.h"  // for quicktime_init
76
77 #include "BPY_extern.h"
78
79 #include "RE_pipeline.h"
80
81 #include "playanim_ext.h"
82 #include "mydevice.h"
83 #include "nla.h"
84 #include "datatoc.h"
85
86 /* for passing information between creator and gameengine */
87 #include "SYS_System.h"
88
89 #include <signal.h>
90
91 #ifdef __FreeBSD__
92 # include <sys/types.h>
93 # include <floatingpoint.h>
94 # include <sys/rtprio.h>
95 #endif
96
97 #ifdef WITH_BINRELOC
98 #include "binreloc.h"
99 #endif
100
101 // from buildinfo.c
102 #ifdef BUILD_DATE
103 extern char * build_date;
104 extern char * build_time;
105 extern char * build_platform;
106 extern char * build_type;
107 #endif
108
109 /*      Local Function prototypes */
110 static void print_help();
111 static void print_version();
112
113
114 /* defined in ghostwinlay and winlay, we can't include carbon here, conflict with DNA */
115 #ifdef __APPLE__
116 extern int checkAppleVideoCard(void);
117 extern void getMacAvailableBounds(short *top, short *left, short *bottom, short *right);
118 extern void     winlay_get_screensize(int *width_r, int *height_r);
119 extern void     winlay_process_events(int wait_for_event);
120 #endif
121
122
123 /* for the callbacks: */
124
125 extern int pluginapi_force_ref(void);  /* from blenpluginapi:pluginapi.c */
126
127 char bprogname[FILE_MAXDIR+FILE_MAXFILE]; /* from blenpluginapi:pluginapi.c */
128 char btempdir[FILE_MAXDIR+FILE_MAXFILE];
129
130 /* Initialise callbacks for the modules that need them */
131 void setCallbacks(void); 
132
133 #if defined(__sgi) || defined(__alpha__)
134 static void fpe_handler(int sig)
135 {
136         // printf("SIGFPE trapped\n");
137 }
138 #endif
139
140 /* handling ctrl-c event in console */
141 static void blender_esc(int sig)
142 {
143         static int count = 0;
144         
145         G.afbreek = 1;  /* forces render loop to read queue, not sure if its needed */
146         
147         if (sig == 2) {
148                 if (count) {
149                         printf("\nBlender killed\n");
150                         exit(2);
151                 }
152                 printf("\nSent an internal break event. Press ^C again to kill Blender\n");
153                 count++;
154         }
155 }
156
157 static void print_version(void)
158 {
159 #ifdef BUILD_DATE
160         printf ("Blender %d.%02d (sub %d) Build\n", G.version/100, G.version%100, BLENDER_SUBVERSION);
161         printf ("\tbuild date: %s\n", build_date);
162         printf ("\tbuild time: %s\n", build_time);
163         printf ("\tbuild revision: %s\n", build_rev);
164         printf ("\tbuild platform: %s\n", build_platform);
165         printf ("\tbuild type: %s\n", build_type);
166 #else
167         printf ("Blender %d.%02d (sub %d) Build\n", G.version/100, G.version%100, BLENDER_SUBVERSION);
168 #endif
169 }
170
171 static void print_help(void)
172 {
173         printf ("Blender %d.%02d (sub %d) Build\n", G.version/100, G.version%100, BLENDER_SUBVERSION);
174         printf ("Usage: blender [args ...] [file] [args ...]\n");
175         printf ("\nRender options:\n");
176         printf ("  -b <file>\tRender <file> in background (doesn't load the user defaults .B.blend file)\n");
177         printf ("    -a render frames from start to end (inclusive), only works when used after -b\n");
178         printf ("    -S <name>\tSet scene <name>\n");
179         printf ("    -f <frame>\tRender frame <frame> and save it\n");                          
180         printf ("    -s <frame>\tSet start to frame <frame> (use before the -a argument)\n");
181         printf ("    -e <frame>\tSet end to frame <frame> (use before the -a argument)\n");
182         printf ("    -o <path>\tSet the render path and file name.\n");
183         printf ("      Use // at the start of the path to\n");
184         printf ("        render relative to the blend file.\n");
185         printf ("      The # characters are replaced by the frame number, and used to define zero padding.\n");
186         printf ("        ani_##_test.png becomes ani_01_test.png\n");
187         printf ("        test-######.png becomes test-000001.png\n");
188         printf ("        When the filename has no #, The suffix #### is added to the filename\n");
189         printf ("      The frame number will be added at the end of the filename.\n");
190         printf ("      eg: blender -b foobar.blend -o //render_ -F PNG -x 1 -a\n");
191         printf ("\nFormat options:\n");
192         printf ("    -F <format>\tSet the render format, Valid options are...\n");
193         printf ("    \tTGA IRIS HAMX JPEG MOVIE IRIZ RAWTGA\n");
194         printf ("    \tAVIRAW AVIJPEG PNG BMP FRAMESERVER\n");
195         printf ("    (formats that can be compiled into blender, not available on all systems)\n");
196         printf ("    \tHDR TIFF EXR MULTILAYER MPEG AVICODEC QUICKTIME CINEON DPX DDS\n");
197         printf ("    -x <bool>\tSet option to add the file extension to the end of the file.\n");
198         printf ("    -t <threads>\tUse amount of <threads> for rendering (background mode only).\n");
199         printf ("      [1-8], 0 for systems processor count.\n");
200         printf ("\nAnimation playback options:\n");
201         printf ("  -a <file(s)>\tPlayback <file(s)>, only operates this way when -b is not used.\n");
202         printf ("    -p <sx> <sy>\tOpen with lower left corner at <sx>, <sy>\n");
203         printf ("    -m\t\tRead from disk (Don't buffer)\n");
204         printf ("    -f <fps> <fps-base>\t\tSpecify FPS to start with\n");
205                                 
206         printf ("\nWindow options:\n");
207         printf ("  -w\t\tForce opening with borders (default)\n");
208         printf ("  -W\t\tForce opening without borders\n");
209         printf ("  -p <sx> <sy> <w> <h>\tOpen with lower left corner at <sx>, <sy>\n");
210         printf ("                      \tand width and height <w>, <h>\n");
211         printf ("\nGame Engine specific options:\n");
212         printf ("  -g fixedtime\t\tRun on 50 hertz without dropping frames\n");
213         printf ("  -g vertexarrays\tUse Vertex Arrays for rendering (usually faster)\n");
214         printf ("  -g noaudio\t\tNo audio in Game Engine\n");
215         printf ("  -g nomipmap\t\tNo Texture Mipmapping\n");
216         printf ("  -g linearmipmap\tLinear Texture Mipmapping instead of Nearest (default)\n");
217
218         printf ("\nMisc options:\n");
219         printf ("  -d\t\tTurn debugging on\n");
220         printf ("  -noaudio\tDisable audio on systems that support audio\n");
221         printf ("  -h\t\tPrint this help text\n");
222         printf ("  -y\t\tDisable automatic python script execution (scriptlinks, pydrivers, pyconstraints, pynodes)\n");
223         printf ("  -P <filename>\tRun the given Python script (filename or Blender Text)\n");
224 #ifdef WIN32
225         printf ("  -R\t\tRegister .blend extension\n");
226 #endif
227         printf ("  -v\t\tPrint Blender version and exit\n");
228         printf ("  --\t\tEnds option processing.  Following arguments are \n");
229         printf ("    \t\t   passed unchanged.  Access via Python's sys.argv\n");
230         printf ("\nEnvironment Variables:\n");
231         printf ("  $HOME\t\t\tStore files such as .blender/ .B.blend .Bfs .Blog here.\n");
232 #ifdef WIN32
233         printf ("  $TEMP\t\tStore temporary files here.\n");
234 #else
235         printf ("  $TMP or $TMPDIR\tStore temporary files here.\n");
236         printf ("  $SDL_AUDIODRIVER\tLibSDL audio driver - alsa, esd, alsa, dma.\n");
237         printf ("  $BF_TIFF_LIB\t\tUse an alternative libtiff.so for loading tiff image files.\n");
238 #endif
239         printf ("  $IMAGEEDITOR\t\tImage editor executable, launch with the IKey from the file selector.\n");
240         printf ("  $WINEDITOR\t\tText editor executable, launch with the EKey from the file selector.\n");
241         printf ("  $PYTHONHOME\t\tPath to the python directory, eg. /usr/lib/python.\n");
242         printf ("\nNote: Arguments must be separated by white space. eg:\n");
243         printf ("    \"blender -ba test.blend\"\n");
244         printf ("  ...will ignore the 'a'\n");
245         printf ("    \"blender -b test.blend -f8\"\n");
246         printf ("  ...will ignore 8 because there is no space between the -f and the frame value\n");
247         printf ("Note: Arguments are executed in the order they are given. eg:\n");
248         printf ("    \"blender -b test.blend -f 1 -o /tmp\"\n");
249         printf ("  ...may not render to /tmp because '-f 1' renders before the output path is set\n");
250         printf ("    \"blender -b -o /tmp test.blend -f 1\"\n");
251         printf ("  ...may not render to /tmp because loading the blend file overwrites the output path that was set\n");
252         printf ("    \"blender -b test.blend -o /tmp -f 1\" works as expected.\n\n");
253 }
254
255
256 double PIL_check_seconds_timer(void);
257 extern void winlay_get_screensize(int *width_r, int *height_r);
258
259 static void main_init_screen( void )
260 {
261         setscreen(G.curscreen);
262         
263         if(G.main->scene.first==0) {
264                 set_scene( add_scene("1") );
265         }
266 }
267
268 int main(int argc, char **argv)
269 {
270         int a, i, stax=0, stay=0, sizx, sizy, scr_init = 0;
271         SYS_SystemHandle syshandle;
272
273 #if defined(WIN32) || defined (__linux__)
274         int audio = 1;
275 #else
276         int audio = 0;
277 #endif
278
279         
280 #ifdef WITH_BINRELOC
281         br_init( NULL );
282 #endif
283
284         setCallbacks();
285 #ifdef __APPLE__
286                 /* patch to ignore argument finder gives us (pid?) */
287         if (argc==2 && strncmp(argv[1], "-psn_", 5)==0) {
288                 extern int GHOST_HACK_getFirstFile(char buf[]);
289                 static char firstfilebuf[512];
290                 int scr_x,scr_y;
291
292                 argc= 1;
293
294         /* first let us check if we are hardware accelerated and with VRAM > 16 Mo */
295         
296         if (checkAppleVideoCard()) {
297                         short top, left, bottom, right;
298                         
299                         winlay_get_screensize(&scr_x, &scr_y); 
300                         getMacAvailableBounds(&top, &left, &bottom, &right);
301                         setprefsize(left +10,scr_y - bottom +10,right-left -20,bottom - 64, 0);
302
303         } else {
304                                 winlay_get_screensize(&scr_x, &scr_y);
305
306                 /* 40 + 684 + (headers) 22 + 22 = 768, the powerbook screen height */
307                 setprefsize(120, 40, 850, 684, 0);
308         }
309     
310                 winlay_process_events(0);
311                 if (GHOST_HACK_getFirstFile(firstfilebuf)) {
312                         argc= 2;
313                         argv[1]= firstfilebuf;
314                 }
315         }
316
317 #endif
318
319 #ifdef __FreeBSD__
320         fpsetmask(0);
321 #endif
322 #ifdef __linux__
323     #ifdef __alpha__
324         signal (SIGFPE, fpe_handler);
325     #else
326         if ( getenv("SDL_AUDIODRIVER") == NULL) {
327                 setenv("SDL_AUDIODRIVER", "alsa", 1);
328         }
329     #endif
330 #endif
331 #if defined(__sgi)
332         signal (SIGFPE, fpe_handler);
333 #endif
334
335         // copy path to executable in bprogname. playanim and creting runtimes
336         // need this.
337
338         BLI_where_am_i(bprogname, argv[0]);
339         
340                 /* Hack - force inclusion of the plugin api functions,
341                  * see blenpluginapi:pluginapi.c
342                  */
343         pluginapi_force_ref();
344         
345         init_nodesystem();
346         
347         initglobals();  /* blender.c */
348
349         syshandle = SYS_GetSystem();
350         GEN_init_messaging_system();
351
352         /* first test for background */
353
354         G.f |= G_DOSCRIPTLINKS; /* script links enabled by default */
355
356         for(a=1; a<argc; a++) {
357
358                 /* Handle unix and windows style help requests */
359                 if ((!strcmp(argv[a], "--help")) || (!strcmp(argv[a], "/?"))){
360                         print_help();
361                         exit(0);
362                 }
363
364                 /* end argument processing after -- */
365                 if (!strcmp( argv[a], "--")){
366                         a = argc;
367                         break;
368                 }
369
370                 /* Handle long version request */
371                 if (!strcmp(argv[a], "--version")){
372                         print_version();
373                         exit(0);
374                 }
375
376                 /* Handle -* switches */
377                 else if(argv[a][0] == '-') {
378                         switch(argv[a][1]) {
379                         case 'a': /* -b was not given, play an animation */
380                                 playanim(argc-1, argv+1);
381                                 exit(0);
382                                 break;
383                         case 'b':
384                         case 'B':
385                                 G.background = 1;
386                                 a= argc;
387                                 break;
388
389                         case 'y':
390                                 G.f &= ~G_DOSCRIPTLINKS;
391                                 break;
392
393                         case 'Y':
394                                 printf ("-y was used to disable script links because,\n");
395                                 printf ("\t-p being taken, Ton was of the opinion that Y\n");
396                                 printf ("\tlooked like a split (disabled) snake, and also\n");
397                                 printf ("\twas similar to a python's tongue (unproven).\n\n");
398
399                                 printf ("\tZr agreed because it gave him a reason to add a\n");
400                                 printf ("\tcompletely useless text into Blender.\n\n");
401                                 
402                                 printf ("\tADDENDUM! Ton, in defense, found this picture of\n");
403                                 printf ("\tan Australian python, exhibiting her (his/its) forked\n");
404                                 printf ("\tY tongue. It could be part of an H Zr retorted!\n\n");
405                                 printf ("\thttp://www.users.bigpond.com/snake.man/\n");
406                                 
407                                 exit(252);
408                                 
409                         case 'h':                       
410                                 print_help();
411                                 exit(0);
412                         case 'v':
413                                 print_version();
414                                 exit(0);
415                         default:
416                                 break;
417                         }
418                 }
419         }
420
421 #ifdef __sgi
422         setuid(getuid()); /* end superuser */
423 #endif
424
425         /* for all platforms, even windos has it! */
426         if(G.background) signal(SIGINT, blender_esc);   /* ctrl c out bg render */
427
428         /* background render uses this font too */
429         BKE_font_register_builtin(datatoc_Bfont, datatoc_Bfont_size);
430         
431         init_def_material();
432
433         winlay_get_screensize(&sizx, &sizy);
434         stax=0;
435         stay=0;
436
437         if(G.background==0) {
438                 for(a=1; a<argc; a++) {
439                         if(argv[a][0] == '-') {
440                                 switch(argv[a][1]) {
441                                 case 'p':       /* prefsize */
442                                         if (argc-a < 5) {
443                                                 printf ("-p requires four arguments\n");
444                                                 exit(1);
445                                         }
446                                         a++;
447                                         stax= atoi(argv[a]);
448                                         a++;
449                                         stay= atoi(argv[a]);
450                                         a++;
451                                         sizx= atoi(argv[a]);
452                                         a++;
453                                         sizy= atoi(argv[a]);
454                                         G.windowstate = G_WINDOWSTATE_BORDER;
455
456                                         break;
457                                 case 'd':
458                                         G.f |= G_DEBUG;         /* std output printf's */ 
459                                         printf ("Blender %d.%02d (sub %d) Build\n", G.version/100, G.version%100, BLENDER_SUBVERSION);
460                                         MEM_set_memory_debug();
461 #ifdef NAN_BUILDINFO
462                                         printf("Build: %s %s %s %s\n", build_date, build_time, build_platform, build_type);
463
464 #endif // NAN_BUILDINFO
465                                         for (i = 0; i < argc; i++) {
466                                                 printf("argv[%d] = %s\n", i, argv[i]);
467                                         }
468                                         break;
469             
470                                 case 'w':
471                                         G.windowstate = G_WINDOWSTATE_BORDER;
472                                         break;
473                                 case 'W':
474                                         /* XXX, fixme mein, borderless on OSX */
475                                         G.windowstate = G_WINDOWSTATE_FULLSCREEN;
476                                         break;
477                                 case 'R':
478                                         /* Registering filetypes only makes sense on windows...      */
479 #ifdef WIN32
480                                         RegisterBlendExtension(argv[0]);
481 #endif
482                                         break;
483                                 case 'n':
484                                 case 'N':
485                                         if (BLI_strcasecmp(argv[a], "-noaudio") == 0|| BLI_strcasecmp(argv[a], "-nosound") == 0) {
486                                                 /**
487                                                         notify the gameengine that no audio is wanted, even if the user didn't give
488                                                         the flag -g noaudio.
489                                                 */
490
491                                                 SYS_WriteCommandLineInt(syshandle,"noaudio",1);
492                                                 audio = 0;
493                                                 if (G.f & G_DEBUG) printf("setting audio to: %d\n", audio);
494                                         }
495                                         break;
496                                 }
497                         }
498                 }
499
500                 if ( (G.windowstate == G_WINDOWSTATE_BORDER) || (G.windowstate == G_WINDOWSTATE_FULLSCREEN)) 
501                         setprefsize(stax, stay, sizx, sizy, 0);
502                 
503                 BPY_start_python(argc, argv);
504                 
505                 /**
506                  * NOTE: sound_init_audio() *must be* after start_python,
507                  * at least on FreeBSD.
508                  * added note (ton): i removed it altogether
509                  */
510
511                 BIF_init(); /* loads .B.blend */
512                 
513                 BLI_where_is_temp( btempdir, 1 ); /* call after loading the .B.blend so we can read U.tempdir */
514
515         }
516         else {
517                 BPY_start_python(argc, argv);
518                 
519                 BLI_where_is_temp( btempdir, 0 ); /* call after loading the .B.blend so we can read U.tempdir */
520                 
521                 // (ton) Commented out. I have no idea whats thisfor... will mail around!
522                 // SYS_WriteCommandLineInt(syshandle,"noaudio",1);
523         // audio = 0;
524         // sound_init_audio();
525         // if (G.f & G_DEBUG) printf("setting audio to: %d\n", audio);
526         }
527
528         /**
529          * NOTE: the U.pythondir string is NULL until BIF_init() is executed,
530          * so we provide the BPY_ function below to append the user defined
531          * pythondir to Python's sys.path at this point.  Simply putting
532          * BIF_init() before BPY_start_python() crashes Blender at startup.
533          * Update: now this function also inits the bpymenus, which also depend
534          * on U.pythondir.
535          */
536         BPY_post_start_python();
537
538 #ifdef WITH_QUICKTIME
539
540         quicktime_init();
541
542 #endif /* WITH_QUICKTIME */
543
544         /* dynamically load libtiff, if available */
545         libtiff_init();
546         if (!G.have_libtiff && (G.f & G_DEBUG)) {
547                 printf("Unable to load: libtiff.\n");
548                 printf("Try setting the BF_TIFF_LIB environment variable if you want this support.\n");
549                 printf("Example: setenv BF_TIFF_LIB /usr/lib/libtiff.so\n");
550         }
551
552         /* OK we are ready for it */
553
554         for(a=1; a<argc; a++) {
555                 if (G.afbreek==1) break;
556
557                 if(argv[a][0] == '-') {
558                         switch(argv[a][1]) {
559                         case '-':  /* -- ends argument processing */
560                                 a = argc;
561                                 break;
562                                 
563                         case 'p':       /* prefsize */
564                                 a+= 4;
565                                 break;
566
567                         case 'g':
568                                 {
569                                 /**
570                                 gameengine parameters are automaticly put into system
571                                 -g [paramname = value]
572                                 -g [boolparamname]
573                                 example:
574                                 -g novertexarrays
575                                 -g maxvertexarraysize = 512
576                                 */
577
578                                         if(++a < argc)
579                                         {
580                                                 char* paramname = argv[a];
581                                                 /* check for single value versus assignment */
582                                                 if (a+1 < argc && (*(argv[a+1]) == '='))
583                                                 {
584                                                         a++;
585                                                         if (a+1 < argc)
586                                                         {
587                                                                 a++;
588                                                                 /* assignment */
589                                                                 SYS_WriteCommandLineString(syshandle,paramname,argv[a]);
590                                                         }  else
591                                                         {
592                                                                 printf("error: argument assignment (%s) without value.\n",paramname);
593                                                         }
594                                                         /* name arg eaten */
595
596                                                 } else
597                                                 {
598                                                         SYS_WriteCommandLineInt(syshandle,argv[a],1);
599
600                                                         /* doMipMap */
601                                                         if (!strcmp(argv[a],"nomipmap"))
602                                                         {
603                                                                 set_mipmap(0); //doMipMap = 0;
604                                                         }
605                                                         /* linearMipMap */
606                                                         if (!strcmp(argv[a],"linearmipmap"))
607                                                         {
608                                                                 set_linear_mipmap(1); //linearMipMap = 1;
609                                                         }
610
611
612                                                 } /* if (*(argv[a+1]) == '=') */
613                                         } /*    if(++a < argc)  */
614                                         break;
615                                 }
616                         case 'f':
617                                 a++;
618                                 if (G.scene) {
619                                         if (a < argc) {
620                                                 int frame= MIN2(MAXFRAME, MAX2(1, atoi(argv[a])));
621                                                 Render *re= RE_NewRender(G.scene->id.name);
622                                                 RE_BlenderAnim(re, G.scene, frame, frame);
623                                         }
624                                 } else {
625                                         printf("\nError: no blend loaded. cannot use '-f'.\n");
626                                 }
627                                 break;
628                         case 'a':
629                                 if (G.scene) {
630                                         Render *re= RE_NewRender(G.scene->id.name);
631                                         RE_BlenderAnim(re, G.scene, G.scene->r.sfra, G.scene->r.efra);
632                                 } else {
633                                         printf("\nError: no blend loaded. cannot use '-a'.\n");
634                                 }
635                                 break;
636                         case 'S':
637                                 if(++a < argc) {
638                                         set_scene_name(argv[a]);
639                                 }
640                                 break;
641                         case 's':
642                                 a++;
643                                 if(G.scene) {
644                                         int frame= MIN2(MAXFRAME, MAX2(1, atoi(argv[a])));
645                                         if (a < argc) (G.scene->r.sfra) = frame;
646                                 } else {
647                                         printf("\nError: no blend loaded. cannot use '-s'.\n");
648                                 }
649                                 break;
650                         case 'e':
651                                 a++;
652                                 if(G.scene) {
653                                         int frame= MIN2(MAXFRAME, MAX2(1, atoi(argv[a])));
654                                         if (a < argc) (G.scene->r.efra) = frame;
655                                 } else {
656                                         printf("\nError: no blend loaded. cannot use '-e'.\n");
657                                 }
658                                 break;
659                         case 'P':
660                                 a++;
661                                 if (a < argc) {
662                                         /* If we're not running in background mode, then give python a valid screen */
663                                         if ((G.background==0) && (scr_init==0)) {
664                                                 main_init_screen();
665                                                 scr_init = 1;
666                                         }
667                                         BPY_run_python_script (argv[a]);
668                                 }
669                                 else printf("\nError: you must specify a Python script after '-P '.\n");
670                                 break;
671                         case 'o':
672                                 a++;
673                                 if (a < argc){
674                                         if(G.scene) {
675                                                 BLI_strncpy(G.scene->r.pic, argv[a], FILE_MAXDIR);
676                                         } else {
677                                                 printf("\nError: no blend loaded. cannot use '-o'.\n");
678                                         }
679                                 } else {
680                                         printf("\nError: you must specify a path after '-o '.\n");
681                                 }
682                                 break;
683                         case 'F':
684                                 a++;
685                                 if (a < argc){
686                                         if(!G.scene) {
687                                                 printf("\nError: no blend loaded. order the arguments so '-F ' is after the blend is loaded.\n");
688                                         } else {
689                                                 if      (!strcmp(argv[a],"TGA")) G.scene->r.imtype = R_TARGA;
690                                                 else if (!strcmp(argv[a],"IRIS")) G.scene->r.imtype = R_IRIS;
691                                                 else if (!strcmp(argv[a],"HAMX")) G.scene->r.imtype = R_HAMX;
692 #ifdef WITH_DDS
693                                                 else if (!strcmp(argv[a],"DDS")) G.scene->r.imtype = R_DDS;
694 #endif
695                                                 else if (!strcmp(argv[a],"JPEG")) G.scene->r.imtype = R_JPEG90;
696                                                 else if (!strcmp(argv[a],"MOVIE")) G.scene->r.imtype = R_MOVIE;
697                                                 else if (!strcmp(argv[a],"IRIZ")) G.scene->r.imtype = R_IRIZ;
698                                                 else if (!strcmp(argv[a],"RAWTGA")) G.scene->r.imtype = R_RAWTGA;
699                                                 else if (!strcmp(argv[a],"AVIRAW")) G.scene->r.imtype = R_AVIRAW;
700                                                 else if (!strcmp(argv[a],"AVIJPEG")) G.scene->r.imtype = R_AVIJPEG;
701                                                 else if (!strcmp(argv[a],"PNG")) G.scene->r.imtype = R_PNG;
702                                                 else if (!strcmp(argv[a],"AVICODEC")) G.scene->r.imtype = R_AVICODEC;
703                                                 else if (!strcmp(argv[a],"QUICKTIME")) G.scene->r.imtype = R_QUICKTIME;
704                                                 else if (!strcmp(argv[a],"BMP")) G.scene->r.imtype = R_BMP;
705                                                 else if (!strcmp(argv[a],"HDR")) G.scene->r.imtype = R_RADHDR;
706                                                 else if (!strcmp(argv[a],"TIFF")) G.scene->r.imtype = R_TIFF;
707 #ifdef WITH_OPENEXR
708                                                 else if (!strcmp(argv[a],"EXR")) G.scene->r.imtype = R_OPENEXR;
709                                                 else if (!strcmp(argv[a],"MULTILAYER")) G.scene->r.imtype = R_MULTILAYER;
710 #endif
711                                                 else if (!strcmp(argv[a],"MPEG")) G.scene->r.imtype = R_FFMPEG;
712                                                 else if (!strcmp(argv[a],"FRAMESERVER")) G.scene->r.imtype = R_FRAMESERVER;
713                                                 else if (!strcmp(argv[a],"CINEON")) G.scene->r.imtype = R_CINEON;
714                                                 else if (!strcmp(argv[a],"DPX")) G.scene->r.imtype = R_DPX;
715                                                 else printf("\nError: Format from '-F' not known or not compiled in this release.\n");
716                                         }
717                                 } else {
718                                         printf("\nError: no blend loaded. cannot use '-x'.\n");
719                                 }
720                                 break;
721                                 
722                         case 't':
723                                 a++;
724                                 if(G.background) {
725                                         RE_set_max_threads(atoi(argv[a]));
726                                 } else {
727                                         printf("Warning: threads can only be set in background mode\n");
728                                 }
729                                 break;
730                         case 'x': /* extension */
731                                 a++;
732                                 if (a < argc) {
733                                         if(G.scene) {
734                                                 if (argv[a][0] == '0') {
735                                                         G.scene->r.scemode &= ~R_EXTENSION;
736                                                 } else if (argv[a][0] == '1') {
737                                                         G.scene->r.scemode |= R_EXTENSION;
738                                                 } else {
739                                                         printf("\nError: Use '-x 1' or '-x 0' To set the extension option.\n");
740                                                 }
741                                         } else {
742                                                 printf("\nError: no blend loaded. order the arguments so '-o ' is after '-x '.\n");
743                                         }
744                                 } else {
745                                         printf("\nError: you must specify a path after '- '.\n");
746                                 }
747                                 break;
748                         }
749                 }
750                 else {
751                         
752                         /* Make the path absolute because its needed for relative linked blends to be found */
753                         int abs = 0;
754                         int filelen;
755                         char cwd[FILE_MAXDIR + FILE_MAXFILE];
756                         char filename[FILE_MAXDIR + FILE_MAXFILE];
757                         cwd[0] = filename[0] = '\0';
758                         
759                         BLI_strncpy(filename, argv[a], sizeof(filename));
760                         filelen = strlen(filename);
761                         
762                         /* relative path checks, could do more tests here... */
763 #ifdef WIN32
764                         /* Account for X:/ and X:\ - should be enough */
765                         if (filelen >= 3 && filename[1] == ':' && (filename[2] == '\\' || filename[2] == '/'))
766                                 abs = 1;
767 #else
768                         if (filelen >= 2 && filename[0] == '/')
769                                 abs = 1 ;
770 #endif
771                         if (!abs) {
772                                 BLI_getwdN(cwd); /* incase the full path to the blend isnt used */
773                                 
774                                 if (cwd[0] == '\0') {
775                                         printf(
776                                         "Could not get the current working directory - $PWD for an unknown reason.\n\t"
777                                         "Relative linked files will not load if the entire blend path is not used.\n\t"
778                                         "The 'Play' button may also fail.\n"
779                                         );
780                                 } else {
781                                         /* uses the blend path relative to cwd important for loading relative linked files.
782                                         *
783                                         * cwd should contain c:\ etc on win32 so the relbase can be NULL
784                                         * relbase being NULL also prevents // being misunderstood as relative to the current
785                                         * blend file which isnt a feature we want to use in this case since were dealing
786                                         * with a path from the command line, rather then from inside Blender */
787                                         
788                                         BLI_make_file_string(NULL, filename, cwd, argv[a]); 
789                                 }
790                         }
791                         
792                         if (G.background) {
793                                 int retval = BKE_read_file(filename, NULL);
794                                 sound_initialize_sounds();
795                                 
796                                 /*we successfully loaded a blend file, get sure that
797                                 pointcache works */
798                                 if (retval!=0) G.relbase_valid = 1;
799
800                                 /* happens for the UI on file reading too */
801                                 BKE_reset_undo();
802                                 BKE_write_undo("original");     /* save current state */
803                         } else {
804                                 /* we are not running in background mode here, but start blender in UI mode with 
805                                    a file - this should do everything a 'load file' does */
806                                 BIF_read_file(filename);
807                         }
808                 }
809         }
810
811         if(G.background) {
812                 /* actually incorrect, but works for now (ton) */
813                 exit_usiblender();
814         }
815         
816         if (scr_init==0) {
817                 main_init_screen();
818         }
819         
820         screenmain(); /* main display loop */
821
822         return 0;
823 } /* end of int main(argc,argv) */
824
825 static void error_cb(char *err)
826 {
827         error("%s", err);
828 }
829
830 static void mem_error_cb(char *errorStr)
831 {
832         fprintf(stderr, errorStr);
833         fflush(stderr);
834 }
835
836 void setCallbacks(void)
837 {
838         /* Error output from the alloc routines: */
839         MEM_set_error_callback(mem_error_cb);
840
841
842         /* BLI_blenlib: */
843
844         BLI_setErrorCallBack(error_cb); /* */
845         BLI_setInterruptCallBack(blender_test_break);
846
847 }