Module API_related
[hide private]
[frames] | no frames]

Source Code for Module API_related

  1  # This is not a real module, it's simply an introductory text. 
  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   This is a new kind of script linked to spaces in a given window.  Right now 
188   only the 3D View has the necessary hooks, but the plan is to add access to 
189   other types, too.  Just to clarify naming conventions: in Blender, a screen 
190   is partitioned in windows (also called areas) and each window can show any 
191   space.  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 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 DRAW handler:: 
206   
207    # SPACEHANDLER.VIEW3D.DRAW 
208   
209   Available space handlers can be toggled "on" or "off" in the space header's 
210   B{View->Space Handler Scripts} submenu, by the user. 
211   
212   EVENT space handler scripts are called by that space's event handling callback 
213   in Blender.  The script receives the event B{before} it is further processed 
214   by the program.  An EVENT handler script should check Blender.event (compare 
215   it against L{Draw} events) and either: 
216    - process it (the script must set Blender.event to None then); 
217    - ignore it. 
218   
219   Setting C{Blender.event = None} tells Blender not to go on processing itself 
220   the event, because it was grabbed by the script. 
221   
222   Example:: 
223   
224    # SPACEHANDLER.VIEW3D.EVENT 
225   
226    import Blender 
227    from Blender import Draw 
228    evt = Blender.event 
229    val = Blender.eventValue 
230    return_it = False 
231   
232    if evt == Draw.LEFTMOUSE: 
233      print "Swallowing the left mouse button press" 
234    elif evt == Draw.AKEY: 
235      print "Swallowing an 'a' character" 
236    else: 
237      print "Let the 3D View itself process this event: %d with value %d" % (evt, val) 
238      return_it = True 
239   
240    # if Blender should not process itself the passed event: 
241    if not return_it: Blender.event = None 
242   
243   DRAW space handlers are called by that space's drawing callback in Blender. 
244   The script is called B{after} the space has been drawn. 
245   
246   Two of the L{Blender} module variables related to script links assume 
247   different roles for space handlers: 
248    - B{bylink} is the same: True if the script is running as a script link; 
249    - B{link}: integer from the L{Blender}.SpaceHandlers constant dictionary, 
250      tells what space this handler belongs to and the handler's type 
251      (EVENT, DRAW); 
252    - B{event}: 
253       - EVENT handlers: an input event (check keys and mouse events in 
254         L{Draw}) to be processed or ignored; 
255       - DRAW handlers: 0 always; 
256    - B{eventValue}: 
257       - EVENT handlers: the event value, it indicates mouse button or key 
258         presses (since we don't pass releases) as 1 and mouse movements 
259         (Draw.MOUSE.X and Draw.MOUSE.Y) as the current x or y coordinate, 
260         for example; 
261       - DRAW handlers: 0 always. 
262   
263   B{Guidelines (important)}: 
264    - EVENT handlers can access and change Blender objects just like any other 
265      script, but they should not draw to the screen, B{use a DRAW handler to do 
266      that}.  Specifically: L{Draw.Image} and the L{BGL} drawing functions 
267      should not be used inside an EVENT handler. 
268    - DRAW handlers should leave the space in the same state it was before they 
269      were executed.  OpenGL attributes and the modelview and projection matrices 
270      are automatically saved (pushed) before a DRAW handler runs and restored 
271      (popped) after it finishes, no need to worry about that.  Draw handlers 
272      should not grab events; 
273    - If script handlers need to pass information to each other (for example an 
274      EVENT handler passing info to a DRAW handler), use the L{Registry} module. 
275    - in short: use the event handler to deal with events and the draw handler to 
276      draw and your script will be following the recommended practices for 
277      Blender code. 
278   
279   Registering scripts: 
280   ==================== 
281   
282   To be registered a script needs two things: 
283     - to be either in the default scripts directory or in the user defined scripts 
284       path (see User Preferences window -> File Paths tab -> Python path); 
285     - to have a proper header. 
286   
287   Try 'blender -d' to know where your default directory for scripts is, it will 
288   inform either the directory or the file with that info already parsed, which is 
289   in the same directory of the scripts folder. 
290   
291   The header should be like this one (all double and single apostrophes below 
292   are required):: 
293    #!BPY 
294   
295    # \"\"\" 
296    # Name: 'Script Name' 
297    # Blender: 233 
298    # Group: 'Export' 
299    # Submenu: 'All' all 
300    # Submenu: 'Selected' sel 
301    # Submenu: 'Configure (gui)' gui 
302    # Tooltip: 'Export to some format.' 
303    # \"\"\" 
304   
305   where: 
306    - B{Name} is the string that will appear in the menu; 
307    - B{Blender} is the minimum program version required to run the script; 
308    - B{Group} defines where the script will be put, see all groups in the 
309      Scripts Window's header, menu "Scripts"; 
310    - B{Submenu} adds optional submenus for further control; 
311    - B{Tooltip} is the (short) tooltip string for the menu entry. 
312   
313   note: 
314    - all double and single apostrophes above are required; 
315    - you can "comment out" the header above, by starting lines with 
316      '#', like we did.  This is not required (except for the first line, #!BPY, 
317      of course), but this way the header won't conflict with Python tools that 
318      you can use to generate documentation for your script code.  Just 
319      remember to keep this header above any other line with triple 
320      double-quotes (\"\"\") in your script. 
321   
322   Submenu lines are not required, use them if you want to provide extra 
323   options.  To see which submenu the user chose, check the "__script__" 
324   dictionary in your code: __script__['arg'] has the defined keyword (the word 
325   after the submenu string name: all, sel or gui in the example above) of the 
326   chosen submenu.  For example, if the user clicked on submenu 'Selected' above, 
327   __script__['arg'] will be "sel". 
328   
329   If your script requires extra data or configuration files, there is a special 
330   folder where they can be saved: see 'datadir' in L{Blender.Get}. 
331   
332   
333   Documenting scripts: 
334   ==================== 
335   
336   The "Scripts Help Browser" script in the Help menu can parse special variables 
337   from registered scripts and display help information for users.  For that, 
338   authors only need to add proper information to their scripts, after the 
339   registration header. 
340   
341   The expected variables: 
342   
343    - __bpydoc__ (or __doc__) (type: string): 
344      - The main help text.  Write a first short paragraph explaining what the 
345        script does, then add the rest of the help text, leaving a blank line 
346        between each new paragraph.  To force line breaks you can use <br> tags. 
347   
348    - __author__ (type: string or list of strings): 
349      - Author name(s). 
350   
351    - __version__ (type: string): 
352      - Script version.  A good recommendation is using a version number followed 
353        by the date in the format YYYY/MM/DD: "1.0 2005/12/31". 
354   
355    - __url__ (type: string or list of strings): 
356      - Internet links that are shown as buttons in the help screen.  Clicking 
357        them opens the user's default browser at the specified location.  The 
358        expected format for each url entry is e.g. 
359        "Author's site, http://www.somewhere.com".  The first part, before the 
360        comma (','), is used as the button's tooltip.  There are two preset 
361        options: "blender" and "blenderartists.org", which link to the Python forums at 
362        blender.org and blenderartists.org, respectively. 
363   
364    - __email__ (optional, type: string or list of strings): 
365      - Equivalent to __url__, but opens the user's default email client.  You 
366        can write the email as someone:somewhere*com and the help script will 
367        substitute accordingly: someone@somewhere.com.  This is only a minor help 
368        to hide emails from spammers, since your script may be available at some 
369        site.  "scripts" is the available preset, with the email address of the 
370        mailing list devoted to scripting in Blender, bf-scripts-dev@blender.org. 
371        You should only use this one if you are subscribed to the list: 
372        http://projects.blender.org/mailman/listinfo/bf-scripts-dev for more 
373        information. 
374   
375   Example:: 
376     __author__ = 'Mr. Author' 
377     __version__ = '1.0 2005/01/01' 
378     __url__ = ["Author's site, http://somewhere.com", 
379         "Support forum, http://somewhere.com/forum/", "blender", "blenderartists.org"] 
380     __email__ = ["Mr. Author, mrauthor:somewhere*com", "scripts"] 
381     __bpydoc__ = \"\"\"\\ 
382     This script does this and that. 
383   
384     Explaining better, this script helps you create ... 
385   
386     You can write as many paragraphs as needed. 
387   
388     Shortcuts:<br> 
389       Esc or Q: quit.<br> 
390       etc. 
391   
392     Supported:<br> 
393       Meshes, metaballs. 
394   
395     Known issues:<br> 
396       This is just an example, there's no actual script. 
397   
398     Notes:<br> 
399       You can check scripts bundled with Blender to see more examples of how to 
400      add documentation to your own works. 
401   \"\"\" 
402   
403   B{Note}: your own GUI or menu code can display documentation by calling the 
404   help browser with the L{Blender.ShowHelp} function. 
405   
406   Configuring scripts: 
407   ==================== 
408   
409   The L{Blender.Registry<Registry>} module provides a simplified way to keep 
410   scripts configuration options in memory and also saved in config files. 
411   And with the "Scripts Config Editor" script in the System menu users can later  
412   view and edit the options easily. 
413   
414   Let's first clarify what we mean by config options: they are simple data 
415   (bools, ints, floats, strings) used by programs to conform to user 
416   preferences.  The buttons in Blender's User Preferences window are a good 
417   example. 
418   
419   For example, a particular exporter might include: 
420     - SEPARATE_MATS = False: a bool variable (True / False) to determine if it 
421       should write materials to a separate file; 
422     - VERSION = 2: an int to define an specific version of the export format; 
423     - TEX_DIR = "/path/to/textures": a default texture dir to prepend to all 
424       exported texture filenames instead of their actual paths. 
425   
426   The script needs to provide users a GUI to configure these options -- or else 
427   directly editing the source code would be the only way to change them.  And to 
428   store changes made to the GUI so they can be reloaded any time the script is 
429   executed, programmers have to write and load their own config files (ideally at 
430   L{Blender.Get}('udatadir') or, if not available, L{Blender.Get}('datadir')). 
431   
432   This section describes BPython facilities (based on the L{Registry} module and 
433   the config editor) that can take care of this in a simplified (and much 
434   recommended) way. 
435   
436   Here's how it works:: 
437   
438    # sample_exporter.py 
439    import Blender 
440    from Blender import Registry 
441   
442    # First define all config variables with their default values: 
443    SEPARATE_MATERIALS = True 
444    VERSION = True 
445    TEX_DIR = '' 
446    EXPORT_DIR = '' 
447   
448    # Then define a function to update the Registry: 
449    def registry_update(): 
450      # populate a dict with current config values: 
451      d = { 
452        'SEPARATE_MATERIALS': SEPARATE_MATERIALS, 
453        'VERSION': VERSION, 
454        'TEX_DIR': TEX_DIR, 
455        'EXPORT_DIR': EXPORT_DIR 
456      } 
457      # store the key (optional 3rd arg tells if 
458      # the data should also be written to a file): 
459      Registry.SetKey('sample_exporter', d, True) 
460   
461    # (A good convention is to use the script name as Registry key) 
462   
463    # Now we check if our key is available in the Registry or file system: 
464    regdict = Registry.GetKey('sample_exporter', True) 
465   
466    # If this key already exists, update config variables with its values: 
467    if regdict: 
468      try: 
469        SEPARATE_MATERIALS = regdict['SEPARATE_MATERIALS'] 
470        VERSION = regdict['VERSION'] 
471        TEX_DIR = regdict['TEX_DIR'] 
472        EXPORT_DIR = regdict['EXPORT_DIR'] 
473   
474      # if data was corrupted (or a new version of the script changed 
475      # (expanded, removed, renamed) the config vars and users may have 
476      # the old config file around): 
477      except: update_registry() # rewrite it 
478   
479    else: # if the key doesn't exist yet, use our function to create it: 
480      update_registry() 
481   
482    # ... 
483   
484   Hint: nicer code than the simplistic example above can be written by keeping 
485   config var names in a list of strings and using the exec function.  
486   
487   B{Note}: if your script's GUI lets users change config vars, call the 
488   registry_update() function in the button events callback to save the changes. 
489   On the other hand, you don't need to handle configuration 
490   in your own gui, it can be left for the 'Scripts Config Editor', 
491   which should have access to your script's config key as soon as the 
492   above code is executed once (as soon as SetKey is executed). 
493   
494   B{Note} (limits for config vars): strings longer than 300 characters are 
495   clamped and the number of items in dictionaries, sequences and the config key 
496   itself is limited to 60. 
497   
498   
499   Scripts Configuration Editor: 
500   ----------------------------- 
501   
502   This script should be available from the System menu in the Scripts window. 
503   It provides a GUI to view and edit saved configuration data, both from the 
504   Registry dictionary in memory and the scripts config data dir.  This is 
505   useful for all scripts with config vars, but especially for those without GUIs, 
506   like most importers and exporters, since this editor will provide one for them. 
507   
508   The example above already gives a good idea of how the information can be 
509   prepared to be accessible from this editor, but there is more worth knowing: 
510   
511    1. String vars that end with '_dir' or '_file' (can be upper case, too) are 
512    recognized as input boxes for dirs or files and a 'browse' button is added to 
513    their right side, to call the file selector. 
514   
515    2. Both key names and configuration variables names starting with an 
516    underscore ('_') are ignored by the editor.  Programmers can use this feature 
517    for any key or config var that is not meant to be configured by this editor. 
518   
519    3. The following information refers to extra config variables that may be 
520    added specifically to aid the configuration editor script.  To clarify, in the 
521    example code above these variables (the string 'script' and the dictionaries 
522    'tooltips' and 'limits') would appear along with SEPARATE_MATERIALS, VERSION, 
523    TEX_DIR and EXPORT_DIR, wherever they are written. 
524   
525    Minor note: these names are case insensitive: tooltips, TOOLTIPS, etc. are all 
526    recognized. 
527   
528    3.1 The config editor will try to display a 'help' button for a key, to show 
529    documentation for the script that owns it. To find this "owner script", it 
530    will first look for a config variable called 'script', a string containing 
531    the name of the owner Python file (with or without '.py' extension):: 
532   
533     script = 'sample_exporter.py' 
534   
535    If there is no such variable, the editor will check if the file formed by the 
536    key name and the '.py' extension exists. If both alternatives fail, no help 
537    button will be displayed. 
538   
539    3.2 You can define tooltips for the buttons that the editor creates for your 
540    config data (string input, toggle, number sliders).  Simply create a dict 
541    called 'tooltips', where config var names are keys and their tooltips, 
542    values:: 
543   
544     tooltips = { 
545       'EXPORT_DIR': 'default folder where exported files should be saved', 
546       'VERBOSE': 'print info and warning messages to the console', 
547       'SEPARATE_MATERIALS': 'write materials to their own file' 
548     } 
549   
550    3.3 Int and float button sliders need min and max limits.  This can be passed 
551    to the editor via a dict called 'limits' (ivar1, ivar2 and fvar are meant as 
552    extra config vars that might have been in the example code above):: 
553   
554     limits = {'ivar1': [-10, 10], 'ivar2': [0, 100], 'fvar1': [-12.3, 15.4]} 
555   
556    4. The Config Editor itself maintains a Registry key called "General", with 
557    general options relevant to many scripts, like "verbose" to tell if the user 
558    wants messages printed to the console and "confirm overwrite", to know if 
559    a script should ask for confirmation before overwriting files (all exporters 
560    are recommended to access the General key and check this var -- L{sys.exists 
561    <Sys.exists>} tells if files or folders already exist). 
562   
563   Hint: for actual examples, try the ac3d importer and exporter (it's enough to 
564   call them from the menus then cancel with ESC), as those have been updated to 
565   use this config system.  After calling them their config data will be available 
566   in the Config Editor.  We also recommend adding a section about config vars 
567   in your script's help info, as done in the ac3d ones. 
568   
569   L{Back to Main Page<API_intro>} 
570   =============================== 
571  """ 
572