Probe into the Operator of Blender script

Source: Internet
Author: User


Addon (plug-in) is used to extend the functionality of Blende R, as in other software plugin (plug-ins), remove does not affect the operation of the software. Plugins can be added to Blender's user preferences directory, or in the. blend file you are editing. The former requires you to manually open to use, the latter check the Text Editor in the Register box will be loaded when Blender is activated, or by clicking on the Register box next to the Run Script (shortcut ALT + P).

The path to the Blender plugin is C:\Program files\blender foundation\blender\2.76\scripts\addons, I assume you are using the 64-bit version of the 2.76 blender software, and have not modified the installation path. For example, commonly used images as a flat-loaded plug-in corresponding files: io_import_images_as_planes.py, enabled to enter user preferences (shortcut keys CTRL + ALT + U) of the Add-ons Tab, search filter, tick the following box, in the menu A line of Images as Planes is found in File > Import.

The plugin defines one or more operator, which I do not translate into mathematical operators, C + + operators. All of the UI features of Blender are done through operator, and operator can be bound to menus, buttons, or shortcut keys for invocation. The base class for operator is Bpy.types.Operator, which you need to inherit from when customizing operator.

Well, let's learn to write plugins!
To open Blender's Text Editor, I'm assuming you have a preliminary understanding of Blender's interface layout. Text Editor can be used when the Readme, the programmer in contact with the new project works, through the README probably understand its function, similarly, the Blender project will save the current interface at the exit, the other people open, the first glance at the text introduction. You can write your own blog address and name to let others watch the study.

Our first Operator,say hello to blender!

ImportbpyclassHelloworldoperator (bpy.types.Operator): Bl_idname="Wm.hello_world"Bl_label="Hello World"    defExecute (Self, context):Print("Hello world!")return{'finished'}bpy.utils.register_class (helloworldoperator)

Operator before use must register, bl_idname as the name implies, is operator name, writing like package name, with Dot division, point number left name must belong to one of Bpy.ops, in Blender inside the Python console, dir (bpy.ops) List all the names. Bl_idname internal use; Bl_label visible externally. Python does not differentiate between single and double quotes, and it can enclose strings. Or, C + + uses single and double quotes to differentiate characters from strings, but Python interprets them uniformly as strings.

>>> type (bpy.ops)
<class ' Bpy.ops.BPyOps ' >

>>> dir (bpy.ops)
[' Action ', ' anim ', ' armature ', ' boid ', ' brush ', ' buttons ', ' camera ', ' clip ', ' cloth ', ' console ', ' Constraint ', ' curve ', ' C Ycles ', ' dpaint ', ' Ed ', ' Export_anim ', ' Export_mesh ', ' export_scene ', ' file ', ' fluid ', ' font ', ' gpencil ', ' graph ', ' group ', ' image ', ' Import_anim ', ' import_curve ', ' import_image ', ' Import_mesh ', ' import_scene ', ' info ', ' lamp ', ' lattice ', ' Logic ', ' marker ', ' mask ', ' material ', ' mball ', ' mesh ', ' NLA ', ' node ', ' object ', ' outliner ', ' paint ', ' paintcurve ', ' Palett E ', ' particle ', ' pose ', ' poselib ', ' ptcache ', ' render ', ' rigidbody ', ' safe_areas ', ' scene ', ' Screen ', ' script ', ' Sculpt ', ' Sequencer ', ' sketch ', ' sound ', ' surface ', ' text ', ' texture ', ' time ', ' Transform ', ' UI ', ' UV ', ' view2d ', ' view3d ', ' wm ', ' World ']

>>> print ("Hello world!")
Hello world!

>>> Bpy.ops.wm.hello_world ()
Hello world!
{' Finished '}

>>>

A line of print ("Hello world!") line in the script, output Hello world! Information to the console, running directly is not visible to the output results. You can enter the Bpy.ops.wm.hello_world () test in the console like above, and be careful not to have leading spaces.


Here's a little bit of a change to a UI version of HelloWorld.

ImportbpyclassHelloworldoperator (bpy.types.Operator): Bl_idname="Wm.hello_world"Bl_label="Hello World"    defExecute (Self, context):#print ("Hello world!")Self.report ({'INFO'},"Hello world!")return{'finished'}defInvoke (self, Context, event): Wm=Context.window_managerreturnWm.invoke_props_dialog (self) bpy.utils.register_class (helloworldoperator)

Above command line version of HelloWorld, replace Self.report ({' INFO '}, "Hello world!")
In the 3D view, tap the SPACEBAR, enter Hello world to search, note is real-time search, enter a few letters to see the entry. Mouse Click this entry, will pop up a dialog box, the title is Bl_label, click OK Disappears, Blender interface menu A line of logo will toast "Hello world!" message. You can also test the newly defined operator in the Python console by typing Bpy.ops.wm.hello_world ().

>>> Bpy.ops.wm.hello_world ()
Info:hello world!
{' Finished '}

>>>

When the Invoke method completes, it needs to return a collection of strings, which are enclosed in {} to represent a set. Tell Blender operator in the running state {' Running_modal '}, or cancel the operation {' CANCELLED '}, and return {"Finished"} indicates a successful execution.

Second operator, add a positive tetrahedron (regular tetrahedron).
An advantage of the ratio between Chinese and English is ———— Monday to the day, January to December, the tetrahedron to positive 20 is represented by numbers, remember the numbers will be written, and English aside from the numbers, light month There are 12 words, English vocabulary is so increased up.
Regarding the geometrical properties of the tetrahedron, I hope you will remember. The normal tetrahedron is the simplest geometry in three-dimensional space, and the molecular model of methane CH4 can be explained as the tetrahedron, and the carbon atom is the center of the outer surface. The angle of the dihedral angle is arccos (1/3), and the carbon atom is the coordinate origin, then the coordinates of four hydrogen atoms are, and any two hydrogen atoms are 2.

The tetrahedron is also easy to construct from the cube, select the opposite diagonal of the cube, connect the four vertices, it can form a positive tetrahedron. Like this:


System Add Cube/cylinder/sphere etc, in Todo


Blender uses the BU unit, the side length of the tetrahedron is 1, vertex (0, -1/MATH.SQRT (3), 0), (0.5, 1/(2 * MATH.SQRT (3)), 0), ( -0.5, 1/(2 * math.sq RT (3)), 0), (0, 0, math.sqrt (2/3)). The above is constructed with the system's cube (side length 2BU), the edge length is 2*sqrt (2), vertex (1, 1, 1), (-1,-1, 1), (1,-1,-1), (-1, 1,-1), the vertices are all integers oh!

Importbpy fromMathImportsqrt fromMathutilsImportVectorclassMaketetrahedron (bpy.types.Operator): Bl_idname="Mesh.make_tetrahedron"Bl_label="ADD Tetrahedron"    defInvoke (self, Context, event): vertices=[Vector (0,-1/SQRT (3), 0), Vector (0.5, 1/(2 * sqrt (3)) (0)), Vector (-0.5, 1/(2 * sqrt (3), 0), Vector ((0, 0, sqrt (2/3))) ,] edges=[] Faces= [[0, 1, 2], [0, 1, 3], [1, 2, 3], [2, 0, 3]] Tetrahedron= Bpy.data.meshes.new ("Tetrahedron") tetrahedron.from_pydata (vertices, edges, faces) tetrahedron.update () object= Bpy.data.objects.new ("Tetrahedron", tetrahedron) context.scene.objects.link (object)return{"finished"}    #End Invoke#End MaketetrahedrondefRegister (): Bpy.utils.register_class (Maketetrahedron)defunregister (): Bpy.utils.unregister_class (Maketetrahedron)if __name__=="__main__": Register ()

The content of more than one line to write, the individual like the brackets column alignment, you need to add a backslash at the end of the line, to continue, not write will be error. If you do not like this, you can take the next line of parentheses to come up.
Python supports UTF-8 encoding, which means that the class name, method name, variable name can be in Unicode characters, including, of course, Chinese. If you do not know that the English of the tetrahedron is tetrahedron, please do not use pinyin instead. I have seen some new handwritten Java code, do not understand the word too lazy to look up the dictionary, using pinyin (such as factorial function written Jiecheng), look at the want to beat people, you write Chinese, the compiler will not blame you. But then again, it is best to use ASCII characters, note that the code works in American English or British English, other characters can appear in the comments.

The above code first gives the data of the tetrahedron (if only for a tetrahedron, you can Mesh > ADD cone,vertices Select 3), Vertices/edges/faces. The Mesh.from_pydata function uses the v/e/f data to construct a mesh surface. Like C/c++/java, the index is counted from 0, and Matlab/lua is counted starting from 1. Counting starting from 0 is a lot of good. The faces data is provided above, edges is left blank, representing the solid (solid) model, and if the following data is provided, the wireframe (wireframe) model of the tetrahedron is obtained.

    # same as above    edges = [[0, 1], [0, 2], [0, 3], [1, 2], [2, 3], [3, 1]]    = []

Note that either provide edges data, or provide faces data, both of which are likely to cause Blender to crash. (Well, I told you a way to crash blender.) After importing v/e/f, the Mesh data is changed and needs to be updated ().

The mesh is created, and the next mesh is attached to object DataBlock, which is finally linked to the scene. Okay, we're done. The last sentence of the registration register_class when necessary, or press space is not searchable.

I assume that you are familiar with the Python language, know the way the class inherits, and know the meaning of indentation. If you get a syntax error when you run it, Blender will pop up and the window may be mixed with tabs and spaces, corrected and re-executed.

Probe into the Operator of Blender script

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.