Manual/PartXV/Python Scripting
Wikipedia,自由的百科全书
Contents |
Python Scripting
Blender has a very powerful yet often overlooked feature. It
exhibits an internal fully fledged Python interpreter.
This allows any user to add functionalities by writing a Python script.
Python is an interpreted, interactive, object-oriented programming language.
It incorporates modules, exceptions, dynamic typing, very high level dynamic
data types, and classes. Python combines remarkable power with very clear
syntax. It was expressly designed to be usable as an extension
language for applications that need a programmable interface, and
this is why Blender uses it.
Of the two main ways of extending Blender, the other one
being binary plugins, Python scripting is more
powerful, versatile yet easier to comprehend and robust.
It is generally preferred to use Python scripting
than writing a plugin.
Actually Python scripting had somewhat limited functionalities
up to Blender 2.25, the last of NaN releases. When Open Sourcing
Blender many of the new developers gathered around the Foundation
elected to work on it and, together with UI change, Python API
is probably the single part of Blender which got the greatest
development. A full reorganization of what existed was carried out
and many new modules added.
This evolution is still ongoing and even better
integration is expected in forthcoming Blender versions.
Blender has a Text Window among its windows types accessible via the
button of the Window Type menu or via SHIFT-F11.
The newly opened Text window is grey and empty, with a very simple
toolbar (Text Toolbar.). From left to right there
are the standard Window type selection button and the Window menu.
Then the full screen button,
followed by a toggle button which shows/hides the line numbers for the text
and the regular Menu Button.
The Menu Button (
) allows you to select which Text buffer is to be displayed, as well
as allowing you to create a new buffer or load a text file.
If you choose to load a file the Text Window tempoarily becomes a File Selection
Window, with the usual functions.
Once a text buffer is in the Text window, this behaves as a very simple text editor.
Typing on the keyboard produces text in the text buffer.
As usual pressing, LMB dragging and releasing LMB
selects text. The following keyboard commands apply:
- ALT-C or CTRL-C - Copy the marked text into the text clipboard;
- ALT-X or CTRL-X - Cut out the marked text into the text clipboard;
- ALT-V or CTRL-V - Paste the text from the clipboard to the cursor in the Text Window;
- ALT-S - Saves the text as a text file, a File Selection Window appears;
- ALT-O - Loads a text, a File Selection Window appears;
- ALT-F - Pops up the Find toolbox;
- SHIFT-ALT-F or RMB - Pops up the File Menu for the Text Window;
- ALT-J - Pops up a Num Button where you can specify a linenumber the cursor will jump to;
- ALT-P - Executes the text as a Python script;
- ALT-U - Undo;
- ALT-R - Redo;
- CTRL-R - Reopen (reloads) the current buffer;
- ALT-M - Converts the content of the text window into 3D text (max 100 chars);
Blender's cut/copy/paste clipboard is separate from Window's clipboard. So normally you cannot cut/paste/copy out from/into Blender. To access your Windows clipboard use SHIFT-CTRL-C SHIFT-CTRL-V To delete a text buffer just press the 'X' button next to the buffer's name, just as you do for materials, etc. The most notable keystroke is ALT-P which makes the content of the buffer being parsed by the internal Python interpreter built into Blender. The next section will present an example of Python scripting. Before going on it is worth noticing that Blender comes with only the bare Python interpreter built in, and with a few Blender-specific modules, those described in **REF** .
| Other usages for the Text window: The text window is handy also when you want to share your .blend files with the community or with your friends. A Text window can be used to write in a README text explaining the contents of your blender file. Much more handy than having it on a separate application. Be sure to keep it visible when saving! If you are sharing the file with the community and you want to share it under some licence you can write the licence in a text window. |
to have access to the standard Python modules you need a complete working Python install. You can download this from http://www.python.org
Setting the PYTHONPATH environment variable
Be sure to check on http://www.blender.org which is the exact Python version which was built into Blender to prevent compatibility issues. Blender must also be made aware of where this full Python installation is. This is done by defining a PYTHONPATH environment variable.
Setting PYTHONPATH on Win95,98,Me
Once you have installed Python in, say, C:\PYTHON22you must open the file C:\AUTOEXEC.BATwith your favourite text editor, add a line:
SET PYTHONPATH=C:\PYTHON22;C:\PYTHON22\DLLS;C:\PYTHON22\LIB;C:\PYTHON22\LIB\LIB-TK
and reboot the system.
Setting PYTHONPATH on WinNT,2000,XP
Once you have installed Python in, say, C:\PYTHON22 Go on the "My Computer" Icon on the desktop, RMB and select Properties. Select the Advanced tab and press the Environment Variables button. Below the System Variables box, (the second box), hit New. If you are not an administrator you might be unable to do that. In this case hit New in the upper box. Now, in the Variable Name box, type PYTHONPATH, in the Variable Value box,type:
C:\PYTHON22;C:\PYTHON22\DLLS;C:\PYTHON22\LIB;C:\PYTHON22\LIB\LIB-TK
Hit OK repeatedly to exit from all dialogs. You may or may not have to reboot, depending on the OS.
Setting PYTHONPATH on Linux and other UNIXes
Normally you will have Python already there. if not, install it. You will have to discover where it is. This is easy, just start a Python interactive shell by opening a shell and by typing python in there. Type the following commands:
>>> import sys >>> print sys.path
and note down the output, it should look like
['', '/usr/local/lib/python2.2', '/usr/local/lib/python2.2 /plat-linux2', '/usr/local/lib/python2.0/lib-tk', '/usr/local/lib/python2.0/lib-dynload', '/usr/local/lib/python2.0/site-packages']
Add this to your favourite rc file as an environment variable setting. For example, add in your .bashrc the line
export PYTHONPATH=/usr/local/lib/python2.2:/usr/local/lib/python2.2/plat-linux2:/usr/local/lib/python2.2/lib-tk:/usr/local/lib/python2.2/lib-dynload:/usr/local/lib/python2.0/site-packages
all on a single line. Open a new login shell, or logoff and login again.
A working Python example
Now that you've seen that Blender is extensible via Python scripting and that you've got the basics of script handling and how to run a script, before smashing your brain with the full python API reference let's have a look at a quick working example. We will present a tiny script to produce polygons. This indeed duplicates somewhat the SPACEAdd>>Mesh>>Circle toolbox option, but will create 'filled' polygons, not just the outline. To make the script simple yet complete it will exhibit a Graphical User Interface (GUI) completely written via Blender's API.
Headers, importing modules and globals.
The first 32 lines of code are listed below
Script header
001 ###################################################### 002 # 003 # Demo Script for Blender 2.3 Guide 004 # 005 ###################################################S68 006 # This script generates polygons. It is quite useless 007 # since you can do polygons with ADD->Mesh->Circle 008 # but it is a nice complete script example, and the 009 # polygons are 'filled' 010 ###################################################### 011 012 ###################################################### 013 # Importing modules 014 ###################################################### 015 016 import Blender 017 from Blender import NMesh 018 from Blender.BGL import * 019 from Blender.Draw import * 020 021 import math 022 from math import * 023 024 # Polygon Parameters 025 T_NumberOfSides = Create(3) 026 T_Radius = Create(1.0) 027 028 # Events 029 EVENT_NOEVENT = 1 030 EVENT_DRAW = 2 031 EVENT_EXIT = 3 032
After the necessary comments with the description of what the script does there is (lines 016-022) the importing of Python modules. Blender is the main Blender Python API module. NMesh is the module providing access to Blender's meshes, while BGL and Draw give access to the OpenGL constants and functions and to Blender's windowing interface, respectively. The math module is Python's mathematical module, but since both the 'math' and the 'os' modules are built into Blender you don't need a full Python install for this! The polygons are defined via the number of sides they have and their radius. These parameters have values which must be defined by the user via the GUI hence lines (025-026) create two 'generic button' objects, with their default starting value. Finally, the GUI objects works with, and generates, events. Events identifier are integers left to the coder to define. It is usually a good practice to define mnemonic names for events, as is done here in lines (029-031).
Drawing the GUI.
The code responsible for drawing the GUI should reside in a draw function (GUI drawing).
GUI drawing
033 ######################################################
034 # GUI drawing
035 ######################################################
036 def draw():
037 global T_NumberOfSides
038 global T_Radius
039 global EVENT_NOEVENT,EVENT_DRAW,EVENT_EXIT
040
041 ########## Titles
042 glClear(GL_COLOR_BUFFER_BIT)
043 glRasterPos2d(8, 103)
044 Text("Demo Polygon Script")
045
046 ######### Parameters GUI Buttons
047 glRasterPos2d(8, 83)
048 Text("Parameters:")
049 T_NumberOfSides = Number("No. of sides: ", EVENT_NOEVENT, 10, 55, 210, 18,
050 T_NumberOfSides.val, 3, 20, "Number of sides of out polygon");
051 T_Radius = Slider("Radius: ", EVENT_NOEVENT, 10, 35, 210, 18,
052 T_Radius.val, 0.001, 20.0, 1, "Radius of the polygon");
053
054 ######### Draw and Exit Buttons
055 Button("Draw",EVENT_DRAW , 10, 10, 80, 18)
056 Button("Exit",EVENT_EXIT , 140, 10, 80, 18)
057
Lines (037-039) merely grant access to global data. The real interesting stuff starts from lines (042-044). The OpenGL window is initialised, and the current position set to x=8, y=103. The origin of this reference is the lower left corner of the script window. Then the title Demo Polygon Script is printed. A further string is written (lines 047-048), then the input buttons for the parameters are created. The first (lines 049-050) is a Num Button, exactly like those in the various Blender Button Windows. For the meaning of all the parameters please refer to the API reference. Basically there is the button label, the event generated by the button, its location (x,y) and its dimensions (width, height), its value, which is a data belonging to the Button object itself, the minimum and maximum allowable values and a text string which will appear as a help while hovering on the button, as a tooltip. Lines (051-052) defines a Num Button with a slider, with a very similar syntax. Lines (055-056) finally create a Draw button which will create the polygon and an Exit button.
Managing Events.(管理事件)
The GUI is not drawn, and will not work, until a proper event handler is written and registered (Handling events).
除非一个专署事件处理器(handler)被写好并注册(Handling events),否则GUI不是被绘制,且不会被运行。
Handling events
058 def event(evt, val): 059 if (evt == QKEY and not val): 060 Exit() 061 062 def bevent(evt): 063 global T_NumberOfSides 064 global T_Radius 065 global EVENT_NOEVENT,EVENT_DRAW,EVENT_EXIT 066 067 ######### Manages GUI events 068 if (evt == EVENT_EXIT): 069 Exit() 070 elif (evt== EVENT_DRAW): 071 Polygon(T_NumberOfSides.val, T_Radius.val) 072 Blender.Redraw() 073 074 Register(draw, event, bevent) 075
Lines (058-060) define the keyboard event handler, here responding to the QKEY with a plain Exit() call. More interesting are lines (062-072), in charge of managing the GUI events. Every time a GUI button is used this function is called, with the event number defined within the button as a parameter. The core of this function is hence a "select" structure executing different codes according to the event number. As a last call, the Register function is invoked. This effectively draws the GUI and starts the event capturing cycle.
(058-060)行定义键盘事件处理,这个程序中将Exit() 绑定到了QKEY键上。 更有趣的地方在(062-072)行,GUI事件的管理部分。每次一个GUI按钮被按下的时候,这个函数将被调用,并传递一个在按钮中已经定义好了的事件编号给这个函数作参数。 这个程序的核心是:根据事件编号,从一个"select"结构执行不同的代码。 比如最后一个调用,Register函数被引用。这会高效的绘制GUI和开始事件捕捉循环。
Mesh handling(Mesh处理)
Finally,
Script header shows the main function, the one
creating the polygon. It is a rather simple mesh editing, but
shows many important points of the Blender's internal data
structure.
最终,Script header 显示一个main函数,它建立一个polygon.这是一个非常简单的mesh编辑,但是它显示了Blender很多重要的内部数据结构。
Script header
076 ###################################################### 077 # Main Body 078 ###################################################### 079 def Polygon(NumberOfSides,Radius): 080 081 ######### Creates a new mesh 082 poly = NMesh.GetRaw() 083 084 ######### Populates it of vertices 085 for i in range(0,NumberOfSides): 086 phi = 3.141592653589 * 2 * i / NumberOfSides 087 x = Radius * cos(phi) 088 y = Radius * sin(phi) 089 z = 0 090 091 v = NMesh.Vert(x,y,z) 092 poly.verts.append(v) 093 094 ######### Adds a new vertex to the center 095 v = NMesh.Vert(0.,0.,0.) 096 poly.verts.append(v) 097 098 ######### Connects the vertices to form faces 099 for i in range(0,NumberOfSides): 100 f = NMesh.Face() 101 f.v.append(poly.verts[i]) 102 f.v.append(poly.verts[(i+1)%NumberOfSides]) 103 f.v.append(poly.verts[NumberOfSides]) 104 poly.faces.append(f) 105 106 ######### Creates a new Object with the new Mesh 107 polyObj = NMesh.PutRaw(poly) 108 109 Blender.Redraw()
The first important line here is number (082). Here a new mesh object, poly is created. The mesh object is constituted of a list of vertices and a list of faces, plus some other interesting stuff. For our purposes the vertices and faces lists are what we need. Of course the newly created mesh is empty. The first cycle (lines 085-092) computes the x,y,z location of the NumberOfSides vertices needed to define the polygon. Being a flat figure it is z=0 for all. Line (091) calls the NMesh method Vert to create a new vertex object of co-ordinates (x,y,z). Such an object is then appended (line 096) in the poly Mesh verts list. Finally (lines 095-096) a last vertex is added in the centre. Lines (099-104) now connects these vertices to make faces. It is not required to create all vertices beforehand and then faces. You can safely create a new face as soon as all its vertices are there. Line (100) creates a new face object. A face object has its own list of vertices v (up to 4) defining it. Lines (101-103) appends three vertices to the originally empty f.v list. The vertices are two subsequent vertices of the polygon and the central vertex. These vertices must be taken from the Mesh verts list. Finally line (104) appends the newly created face to the faces list of our poly mesh.
第一个重要的行是(082)行。这里有一个新的mesh物体,poly被建立。这个mesh物体由一个点列表和一个面列表构成,加上一些其他的有趣的东西。因为我们想要的就是这些点和面的列表。 当然这个新建的mesh是空的。第一个循环(行 085-092) 计算NumberOfSides点的x,y,z位置,用来定义这个polygon。从一个平平的图形,它的z都是0。 行(091)调用NMesh方法的Vert来建立一个新的并列于(x,y,z)的点物体。这样就有一个物体被添加(line 096)在了polymesh的verts 列表里面。 最后 (行 095-096)是一个最后的点,被加到了中心。行 (099-104)现在链接这些点来建立一个面。这不用预先建立所有的点和面。你能安全的建立一个新的面直到它所有的点都在这了。 行(100)建立一个新的面物体。一个面物体由它自己的点列表v (小于 4个)定义自己。行(101-103)添加3个点到原本的空f.v列表上。 这些点是polygon和中间点的2个并发的点。这些点必须从meshverts列表中去得的。 最后行(104)添加这个新建的面到我们的poly mesh的faces列表上。
Conclusions(结论)
If you create a polygon.py file containing the above described code and load it into a Blender text window, as you learned in the previous section, and press ALT-P in that window to run it, you will see the script disappearing and the window turn grey. In the lower left corner the GUI will be drawn (The GUI of our example.).
如果你建立一个polygon.py文件包含上述代码,并且把它调入到Blender的文本窗口(就像你在前面章节中学到的一样), 然后在那个窗口中按下ALT-P键来运行它,你将看到脚本显示出来而且窗口变成灰色。在窗口的左下角GUI将被绘制出来。(参看:GUI窗口的例子)
By selecting, for example, 5 vertices and a radius 0.5, and by pressing the Draw button a pentagon will appear on the xy plane of the 3D window (The result of our example script.).
通过选择,比如,5个点和0.5的半径,然后按下Draw按钮,一个五角形将显示在3D窗口的xy平面上。(参看:例子脚本的结果)
Python Reference(Python参考)
The Full Python Application Programmer Interface of Blender has a reference documentation which is a book by itself. For space reason it is not included here. Here it is :)
完整的Blender的Python程序设计界面有一份参考文档(其实是本书)。 基于空间原因,这里并没有包含。 它在这里 :)
Python Scripts(Python脚本)
There are more than one hundred different scripts for Blender available on the net. As with plugins, scripts are very dynamic, changing interface, functionalities and web location fairly quickly, so for an updated list and for a live link to them please refer to one of the two main Blender sites, www.blender.org or www.elysiun.com.
在网上有100多种不同的Blender脚本。 因为插件,脚步都是非常动态的,界面的改变,功能的改变和地址的改变非常快,所以如果你需要一个升级的列表或者一个有效的链接的话,请参考一两个Blender的主网站, www.blender.org 或 www.elysiun.com.
|


