1
2
3 """
4 Blender Python related features
5 ===============================
6
7 L{Back to Main Page<API_intro>}
8
9
10 Introduction:
11 =============
12
13 This page describes special features available to BPython scripts:
14
15 - Command line mode is accessible with the '-P' and '-b' Blender options.
16 - Registration allows scripts to become available from some pre-defined menus
17 in Blender, like Import, Export, Wizards and so on.
18 - Script links are Blender Texts (scripts) executed when a particular event
19 (redraws, .blend file loading, saving, frame changed, etc.) occurs. Now
20 there are also "Space Handlers" to draw onto or get events from a given
21 space (only 3D View now) in some window.
22 - Proper documentation data is used by the 'Scripts Help Browser' script to
23 show help information for any registered script. Your own GUI can use
24 this facility with the L{Blender.ShowHelp} function.
25 - Configuration is for data in your script that can be tweaked according to
26 user taste or needs. Like documentation, this is another helper
27 functionality -- you don't need to provide a GUI yourself to edit config
28 data.
29
30
31 Command line usage:
32 ===================
33
34 Specifying scripts:
35 -------------------
36
37 The '-P' option followed either by:
38 - a script filename (full pathname if not in the same folder where you run
39 the command);
40 - the name of a Text in a .blend file (that must also be specified)
41 will open Blender and immediately run the given script.
42
43 Example::
44
45 # open Blender and execute the given script:
46 blender -P script.py
47
48 Passing parameters:
49 -------------------
50
51 To pass parameters to the script you can:
52 - write them to a file before running Blender, then make your script parse that file;
53 - set environment variables and access them with the 'os' module:
54
55 Examples with parameters being passed to the script via command line::
56
57 # execute a command like:
58
59 myvar=value blender -P script.py
60
61 # and in script.py access myvar with os.getenv
62 # (os.environ and os.setenv are also useful):
63
64 # script.py:
65 import os
66 val = os.getenv('myvar')
67
68 # To pass multiple parameters, simply write them in sequence,
69 # separated by spaces:
70
71 myvar1=value1 myvar2=value2 mystr="some string data" blender -P script.py
72
73 Background mode:
74 ----------------
75
76 In '-b' mode no windows will be opened: the program will run as a command
77 line tool able to render stills and animations and execute any working Python
78 script with complete access to loaded .blend's file contents. Once the task
79 is completed, the program will exit.
80
81 Background mode examples::
82
83 # Open Blender in background mode with file 'myfile.blend'
84 # and run the script 'script.py':
85
86 blender -b myfile.blend -P script.py
87
88 # Note: a .blend file is always required. 'script.py' can be a file
89 # in the file system or a Blender Text stored in 'myfile.blend'.
90
91 # Let's assume 'script.py' has code to render the current frame;
92 # this line will set the [s]tart and [e]nd (and so the current) frame to
93 # frame 44 and call the script:
94
95 blender -b myfile.blend -s 44 -e 44 -P script.py
96
97 # Using now a script written to render animations, we set different
98 # start and end frames and then execute this line:
99
100 blender -b myfile.blend -s 1 -e 10 -P script.py
101
102 # Note: we can also set frames and define if we want a single image or
103 # an animation in the script body itself, naturally.
104
105 The rendered pictures will be written to the default render folder, that can
106 also be set via BPython (take a look at L{Render.RenderData}). Their
107 names will be the equivalent frame number followed by the extension of the
108 chosen image type: 0001.png, for example. To rename them to something else,
109 coders can use the C{rename} function in the standard 'os' Python module.
110
111 Reminder: if you just need to render, it's not necessary to have a script.
112 Blender can create stills and animations with its own command line arguments.
113 Example:
114 - a single image at frame 44: blender -b myfile.blend -f 44
115 - an animation from frame 1 to 10: blender -b myfile.blend -s 1 -e 10 -a
116
117
118 Script links:
119 =============
120
121 Object script links:
122 --------------------
123
124 Users can link Blender Text scripts and objects to have the script
125 code executed when specific events occur to the objects. For example, if a
126 Camera has an script link set to "FrameChanged", the script will be executed
127 whenever the current frame is changed. Links can either be manually added by
128 users on the Buttons window -> Scripts tab or created by another script (see,
129 for example, L{Object.addScriptLink<Object.Object.addScriptLink>}).
130
131 These are the types which can be linked to scripts:
132 - Camera Data;
133 - Lamp Data;
134 - Materials;
135 - Objects;
136 - Scenes;
137 - Worlds.
138
139 And these are the available event choices:
140 - Redraw;
141 - FrameChanged;
142 - Render;
143 - OnLoad (*);
144 - OnSave (*).
145
146 (*) only available for scenes
147
148 There are three L{Blender} module variables that script link authors should
149 be aware of:
150 - B{bylink}: True if the script is running as a script link;
151 - B{link}: the object the running script was linked to (None if this is
152 not a script link);
153 - B{event}: the event type, if the running script is being executed as a
154 script link.
155
156 Example::
157 #script link
158 import Blender
159 if Blender.bylink: # we're running as a script link
160 print "Event: %s for %s" % (Blender.event, Blender.link)
161
162 B{Important note about "Render" events}:
163
164 Each "Render" script link is executed twice: before rendering and after, for
165 reverting changes and for possible clean up actions. Before rendering,
166 'Blender.event' will be "Render" and after rendering it will be "PostRender".
167
168 Example::
169 # render script link
170 import Blender
171 event = Blender.event
172 if event == "Render":
173 # prepare for rendering
174 create_my_very_detailed_mesh_data()
175 elif event == "PostRender":
176 # done rendering, clean up
177 delete_my_very_detailed_mesh_data()
178
179 As suggested by the example above, this is especially useful for script links
180 that need to generate data only useful while rendering, or in case they need
181 to switch between two mesh data objects, one meant for realtime display and
182 the other, more detailed, for renders.
183
184 Space Handler script links:
185 ---------------------------
186
187 These are scripts linked to spaces in a given window. Right now
188 only the 3D View has the necessary hooks. Just to clarify naming
189 conventions: in Blender, a screen is partitioned in windows (also
190 called areas) and each window can show any space.
191 Spaces are: 3D View, Text Editor, Scripts, Buttons, User Preferences,
192 Oops, etc.
193
194 Space handlers are texts in the Text Editor, like other script links, but they
195 need to have a special header to be recognized -- B{I{the first line in the
196 text file}} must inform:
197 1. that they are space handlers;
198 2. the space they belong to;
199 3. whether they are EVENT, EVENT_RELEASE (EVENT ones reporting key release events) or DRAW handlers.
200
201 Example header for a 3D View EVENT handler::
202
203 # SPACEHANDLER.VIEW3D.EVENT
204
205 Example header for a 3D View EVENT handler that also receives release events::
206
207 # SPACEHANDLER.VIEW3D.EVENT.ALL
208
209 Example header for a 3D View DRAW handler::
210
211 # SPACEHANDLER.VIEW3D.DRAW
212
213 Available space handlers can be toggled "on" or "off" in the space header's
214 B{View->Space Handler Scripts} submenu, by the user.
215
216 EVENT space handler scripts are called by that space's event handling callback
217 in Blender. The script receives the event B{before} it is further processed
218 by the program. An EVENT handler script should check Blender.event (compare
219 it against L{Draw} events) and either:
220 - process it (the script must set Blender.event to None then);
221 - ignore it.
222
223 EVENT ALL space handlers (header: # SPACEHANDLER.VIEW3D.EVENT.ALL) are executed
224 both for key presses (Blender.event = Blender.SpaceHandlers.VIEW3D_EVENT) and
225 for key releases (Blender.event = Blender.SpaceHandlers.VIEW3D_EVENT_RELEASE).
226
227 Setting C{Blender.event = None} tells Blender not to go on processing itself
228 the event, because it was grabbed by the script.
229
230 Example::
231
232 # SPACEHANDLER.VIEW3D.EVENT
233
234 import Blender
235 from Blender import Draw
236 evt = Blender.event
237 val = Blender.eventValue
238 return_it = False
239
240 if evt == Draw.LEFTMOUSE:
241 print "Swallowing the left mouse button press"
242 elif evt == Draw.AKEY:
243 print "Swallowing an 'a' character"
244 else:
245 print "Let the 3D View itself process this event: %d with value %d" % (evt, val)
246 return_it = True
247
248 # if Blender should not process itself the passed event:
249 if not return_it: Blender.event = None
250
251 DRAW space handlers are called by that space's drawing callback in Blender.
252 The script is called B{after} the space has been drawn.
253
254 Two of the L{Blender} module variables related to script links assume
255 different roles for space handlers:
256 - B{bylink} is the same: True if the script is running as a script link;
257 - B{link}: integer from the L{Blender}.SpaceHandlers constant dictionary,
258 tells what space this handler belongs to and the handler's type
259 (EVENT, EVENT_RELEASE, DRAW);
260 - B{event}:
261 - EVENT handlers: an input event (check keys and mouse events in
262 L{Draw}) to be processed or ignored;
263 - DRAW handlers: 0 always;
264 - B{eventValue}:
265 - EVENT handlers: the event value, it indicates mouse button or key
266 presses (since we don't pass releases) as 1 and mouse movements
267 (Draw.MOUSE.X and Draw.MOUSE.Y) as the current x or y coordinate,
268 for example;
269 - EVENT_RELEASE handlers (EVENT handlers executed during key release events): 0;
270 - DRAW handlers: 0 always.
271
272 B{Guidelines (important)}:
273 - EVENT handlers can access and change Blender objects just like any other
274 script, but they should not draw to the screen, B{use a DRAW handler to do
275 that}. Specifically: L{Draw.Image} and the L{BGL} drawing functions
276 should not be used inside an EVENT handler.
277 - DRAW handlers should leave the space in the same state it was before they
278 were executed. OpenGL attributes and the modelview and projection matrices
279 are automatically saved (pushed) before a DRAW handler runs and restored
280 (popped) after it finishes, no need to worry about that. Draw handlers
281 should not grab events;
282 - If script handlers need to pass information to each other (for example an
283 EVENT handler passing info to a DRAW handler), use the L{Registry} module.
284 - in short: use the event handler to deal with events and the draw handler to
285 draw and your script will be following the recommended practices for
286 Blender code.
287
288 Registering scripts:
289 ====================
290
291 To be registered a script needs two things:
292 - to be either in the default scripts directory or in the user defined scripts
293 path (see User Preferences window -> File Paths tab -> Python path);
294 - to have a proper header.
295
296 Try 'blender -d' to know where your default directory for scripts is, it will
297 inform either the directory or the file with that info already parsed, which is
298 in the same directory of the scripts folder.
299
300 The header should be like this one (all double and single apostrophes below
301 are required)::
302 #!BPY
303
304 # \"\"\"
305 # Name: 'Script Name'
306 # Blender: 233
307 # Group: 'Export'
308 # Submenu: 'All' all
309 # Submenu: 'Selected' sel
310 # Submenu: 'Configure (gui)' gui
311 # Tooltip: 'Export to some format.'
312 # \"\"\"
313
314 where:
315 - B{Name} is the string that will appear in the menu;
316 - B{Blender} is the minimum program version required to run the script;
317 - B{Group} defines where the script will be put, see all groups in the
318 Scripts Window's header, menu "Scripts";
319 - B{Submenu} adds optional submenus for further control;
320 - B{Tooltip} is the (short) tooltip string for the menu entry.
321
322 note:
323 - all double and single apostrophes above are required;
324 - you can "comment out" the header above, by starting lines with
325 '#', like we did. This is not required (except for the first line, #!BPY,
326 of course), but this way the header won't conflict with Python tools that
327 you can use to generate documentation for your script code. Just
328 remember to keep this header above any other line with triple
329 double-quotes (\"\"\") in your script.
330
331 Submenu lines are not required, use them if you want to provide extra
332 options. To see which submenu the user chose, check the "__script__"
333 dictionary in your code: __script__['arg'] has the defined keyword (the word
334 after the submenu string name: all, sel or gui in the example above) of the
335 chosen submenu. For example, if the user clicked on submenu 'Selected' above,
336 __script__['arg'] will be "sel".
337
338 If your script requires extra data or configuration files, there is a special
339 folder where they can be saved: see 'datadir' in L{Blender.Get}.
340
341
342 Documenting scripts:
343 ====================
344
345 The "Scripts Help Browser" script in the Help menu can parse special variables
346 from registered scripts and display help information for users. For that,
347 authors only need to add proper information to their scripts, after the
348 registration header.
349
350 The expected variables:
351
352 - __bpydoc__ (or __doc__) (type: string):
353 - The main help text. Write a first short paragraph explaining what the
354 script does, then add the rest of the help text, leaving a blank line
355 between each new paragraph. To force line breaks you can use <br> tags.
356
357 - __author__ (type: string or list of strings):
358 - Author name(s).
359
360 - __version__ (type: string):
361 - Script version. A good recommendation is using a version number followed
362 by the date in the format YYYY/MM/DD: "1.0 2005/12/31".
363
364 - __url__ (type: string or list of strings):
365 - Internet links that are shown as buttons in the help screen. Clicking
366 them opens the user's default browser at the specified location. The
367 expected format for each url entry is e.g.
368 "Author's site, http://www.somewhere.com". The first part, before the
369 comma (','), is used as the button's tooltip. There are two preset
370 options: "blender" and "blenderartists.org", which link to the Python forums at
371 blender.org and blenderartists.org, respectively.
372
373 - __email__ (optional, type: string or list of strings):
374 - Equivalent to __url__, but opens the user's default email client. You
375 can write the email as someone:somewhere*com and the help script will
376 substitute accordingly: someone@somewhere.com. This is only a minor help
377 to hide emails from spammers, since your script may be available at some
378 site. "scripts" is the available preset, with the email address of the
379 mailing list devoted to scripting in Blender, bf-scripts-dev@blender.org.
380 You should only use this one if you are subscribed to the list:
381 http://projects.blender.org/mailman/listinfo/bf-scripts-dev for more
382 information.
383
384 Example::
385 __author__ = 'Mr. Author'
386 __version__ = '1.0 2005/01/01'
387 __url__ = ["Author's site, http://somewhere.com",
388 "Support forum, http://somewhere.com/forum/", "blender", "blenderartists.org"]
389 __email__ = ["Mr. Author, mrauthor:somewhere*com", "scripts"]
390 __bpydoc__ = \"\"\"\\
391 This script does this and that.
392
393 Explaining better, this script helps you create ...
394
395 You can write as many paragraphs as needed.
396
397 Shortcuts:<br>
398 Esc or Q: quit.<br>
399 etc.
400
401 Supported:<br>
402 Meshes, metaballs.
403
404 Known issues:<br>
405 This is just an example, there's no actual script.
406
407 Notes:<br>
408 You can check scripts bundled with Blender to see more examples of how to
409 add documentation to your own works.
410 \"\"\"
411
412 B{Note}: your own GUI or menu code can display documentation by calling the
413 help browser with the L{Blender.ShowHelp} function.
414
415 Configuring scripts:
416 ====================
417
418 The L{Blender.Registry<Registry>} module provides a simplified way to keep
419 scripts configuration options in memory and also saved in config files.
420 And with the "Scripts Config Editor" script in the System menu users can later
421 view and edit the options easily.
422
423 Let's first clarify what we mean by config options: they are simple data
424 (bools, ints, floats, strings) used by programs to conform to user
425 preferences. The buttons in Blender's User Preferences window are a good
426 example.
427
428 For example, a particular exporter might include:
429 - SEPARATE_MATS = False: a bool variable (True / False) to determine if it
430 should write materials to a separate file;
431 - VERSION = 2: an int to define an specific version of the export format;
432 - TEX_DIR = "/path/to/textures": a default texture dir to prepend to all
433 exported texture filenames instead of their actual paths.
434
435 The script needs to provide users a GUI to configure these options -- or else
436 directly editing the source code would be the only way to change them. And to
437 store changes made to the GUI so they can be reloaded any time the script is
438 executed, programmers have to write and load their own config files (ideally at
439 L{Blender.Get}('udatadir') or, if not available, L{Blender.Get}('datadir')).
440
441 This section describes BPython facilities (based on the L{Registry} module and
442 the config editor) that can take care of this in a simplified (and much
443 recommended) way.
444
445 Here's how it works::
446
447 # sample_exporter.py
448 import Blender
449 from Blender import Registry
450
451 # First define all config variables with their default values:
452 SEPARATE_MATERIALS = True
453 VERSION = True
454 TEX_DIR = ''
455 EXPORT_DIR = ''
456
457 # Then define a function to update the Registry:
458 def registry_update():
459 # populate a dict with current config values:
460 d = {
461 'SEPARATE_MATERIALS': SEPARATE_MATERIALS,
462 'VERSION': VERSION,
463 'TEX_DIR': TEX_DIR,
464 'EXPORT_DIR': EXPORT_DIR
465 }
466 # store the key (optional 3rd arg tells if
467 # the data should also be written to a file):
468 Registry.SetKey('sample_exporter', d, True)
469
470 # (A good convention is to use the script name as Registry key)
471
472 # Now we check if our key is available in the Registry or file system:
473 regdict = Registry.GetKey('sample_exporter', True)
474
475 # If this key already exists, update config variables with its values:
476 if regdict:
477 try:
478 SEPARATE_MATERIALS = regdict['SEPARATE_MATERIALS']
479 VERSION = regdict['VERSION']
480 TEX_DIR = regdict['TEX_DIR']
481 EXPORT_DIR = regdict['EXPORT_DIR']
482
483 # if data was corrupted (or a new version of the script changed
484 # (expanded, removed, renamed) the config vars and users may have
485 # the old config file around):
486 except: update_registry() # rewrite it
487
488 else: # if the key doesn't exist yet, use our function to create it:
489 update_registry()
490
491 # ...
492
493 Hint: nicer code than the simplistic example above can be written by keeping
494 config var names in a list of strings and using the exec function.
495
496 B{Note}: if your script's GUI lets users change config vars, call the
497 registry_update() function in the button events callback to save the changes.
498 On the other hand, you don't need to handle configuration
499 in your own gui, it can be left for the 'Scripts Config Editor',
500 which should have access to your script's config key as soon as the
501 above code is executed once (as soon as SetKey is executed).
502
503 B{Note} (limits for config vars): strings longer than 300 characters are
504 clamped and the number of items in dictionaries, sequences and the config key
505 itself is limited to 60.
506
507
508 Scripts Configuration Editor:
509 -----------------------------
510
511 This script should be available from the System menu in the Scripts window.
512 It provides a GUI to view and edit saved configuration data, both from the
513 Registry dictionary in memory and the scripts config data dir. This is
514 useful for all scripts with config vars, but especially for those without GUIs,
515 like most importers and exporters, since this editor will provide one for them.
516
517 The example above already gives a good idea of how the information can be
518 prepared to be accessible from this editor, but there is more worth knowing:
519
520 1. String vars that end with '_dir' or '_file' (can be upper case, too) are
521 recognized as input boxes for dirs or files and a 'browse' button is added to
522 their right side, to call the file selector.
523
524 2. Both key names and configuration variables names starting with an
525 underscore ('_') are ignored by the editor. Programmers can use this feature
526 for any key or config var that is not meant to be configured by this editor.
527
528 3. The following information refers to extra config variables that may be
529 added specifically to aid the configuration editor script. To clarify, in the
530 example code above these variables (the string 'script' and the dictionaries
531 'tooltips' and 'limits') would appear along with SEPARATE_MATERIALS, VERSION,
532 TEX_DIR and EXPORT_DIR, wherever they are written.
533
534 Minor note: these names are case insensitive: tooltips, TOOLTIPS, etc. are all
535 recognized.
536
537 3.1 The config editor will try to display a 'help' button for a key, to show
538 documentation for the script that owns it. To find this "owner script", it
539 will first look for a config variable called 'script', a string containing
540 the name of the owner Python file (with or without '.py' extension)::
541
542 script = 'sample_exporter.py'
543
544 If there is no such variable, the editor will check if the file formed by the
545 key name and the '.py' extension exists. If both alternatives fail, no help
546 button will be displayed.
547
548 3.2 You can define tooltips for the buttons that the editor creates for your
549 config data (string input, toggle, number sliders). Simply create a dict
550 called 'tooltips', where config var names are keys and their tooltips,
551 values::
552
553 tooltips = {
554 'EXPORT_DIR': 'default folder where exported files should be saved',
555 'VERBOSE': 'print info and warning messages to the console',
556 'SEPARATE_MATERIALS': 'write materials to their own file'
557 }
558
559 3.3 Int and float button sliders need min and max limits. This can be passed
560 to the editor via a dict called 'limits' (ivar1, ivar2 and fvar are meant as
561 extra config vars that might have been in the example code above)::
562
563 limits = {'ivar1': [-10, 10], 'ivar2': [0, 100], 'fvar1': [-12.3, 15.4]}
564
565 4. The Config Editor itself maintains a Registry key called "General", with
566 general options relevant to many scripts, like "verbose" to tell if the user
567 wants messages printed to the console and "confirm overwrite", to know if
568 a script should ask for confirmation before overwriting files (all exporters
569 are recommended to access the General key and check this var -- L{sys.exists
570 <Sys.exists>} tells if files or folders already exist).
571
572 Hint: for actual examples, try the ac3d importer and exporter (it's enough to
573 call them from the menus then cancel with ESC), as those have been updated to
574 use this config system. After calling them their config data will be available
575 in the Config Editor. We also recommend adding a section about config vars
576 in your script's help info, as done in the ac3d ones.
577
578 L{Back to Main Page<API_intro>}
579 ===============================
580 """
581