sample blender add-on cookbook - michelanders.nl

21
Page 2

Upload: others

Post on 30-Jul-2022

4 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Sample Blender Add-On Cookbook - michelanders.nl

Page2

Page 2: Sample Blender Add-On Cookbook - michelanders.nl

This is a sample of my book 

 

Blender Add-on Cookbook 

A cookbook with useful programming recipes for Blender add-ons 

 

If you like to buy a full copy, please visit my Blender Market store: 

https://blendermarket.com/creators/varkenvarken 

In the store you will also find a more gentle introduction to add-ons called  

Creating Add-ons for Blender, a practical primer. 

Page 3: Sample Blender Add-On Cookbook - michelanders.nl

TableofContents

Introduction 5Information 6Addinganobjecttoascene 9Selectingconnectedvertices 13Addamodifiertoanobject 18Addavertexgrouptoanobject 21Changevertex,edgeandfaceproperties 27Changevertex,edgeandfacedatalayers 36CreateaCyclesmaterial 44Addaparticlesystemtoanobject 47Createapropertyselectiondropdown 51Makeafunctionavailabletopydrivers 55Showaprogressbar 58Showinganinfomessage 63Showhintsinanareaheader 66Configurationparametersforadd-ons 69Definingshortcutkeys 73UseNumpytoacceleratevertexmanipulation 77Addingnodestomaterials 82Combiningnodesintoframes 87Addanoperatortoamenu 93Addingpersistentpropertiestoobjects 97Addingsub-menustoexistingmenus 103DrawingusingOpenGL 107Usingapaneltocontrolamodaloperator 114GettingpixelvaluesusingOpenGL 118Convertingbetweenworldandobjectcoordinates 122Usingkd-treestospeedupintersectiontests 127Converting2dscreencoordinatesto3dworldcoordinates 132Converting3dcoordinatesto2dscreencoordinates 136Createamodaloperator 141Usingpassthroughinamodaloperator 144

Page183

Page 4: Sample Blender Add-On Cookbook - michelanders.nl

Changethecursorinamodaloperator 147Packageadd-onswithmorethanonemodule 150Bundlingexternalassetswithyouradd-on 153Addingcustomiconstomenuentries 156WindowmanagementinBlender 161Creatingacurvethroughobjects 165Parentingobjectstocurvevertices 171Acknowledgments 176

Page184

Page 5: Sample Blender Add-On Cookbook - michelanders.nl

BlenderAdd-onCookbook

ByMichelAnders

Copyright2017MichelAnders

BlenderMarketEdition

BlenderMarketEdition,LicenseNotes

Thisebookislicensedforyourpersonalenjoymentonly.Thisebookmaynotbere-soldorgivenawaytootherpeople.Ifyouwouldliketosharethisbookwithanotherperson,

pleasepurchaseanadditionalcopyforeachrecipient.Ifyou’rereadingthisbookanddidnotpurchaseit,oritwasnotpurchasedforyouruseonly,thenpleasereturnto

blendermarket.comandpurchaseyourowncopy.Thankyouforrespectingthehardworkofthisauthor

Page4

Page 6: Sample Blender Add-On Cookbook - michelanders.nl

IntroductionInthelastcoupleofyearIhavecreatednumerousadd-onsandwhileresearchinganddevelopingtheseadd-onsIencounteredallsortsofdifferentissuesthatwherenotalwaysverystraightforwardtosolve.

BlenderhasofcourseextensivedocumentationonitsPythonAPIandahelpfulcommunityaswellbutsometimesitneverthelesstookquitesometimetofiguresomethingout.

SoIdecidedtodocumenttheseissuesandbundlethenintothisbook,whereyouwillfindquiteacollectionofsolutionstocommonlyoccurringissues.Someareobviousonceyouseeandunderstandthem,othersshowcasesubtletiesthatoftenprovetocausetroubleinunexpectedplacesifyouarenotawareofthem.

Ihavedonemybesttoprovidenotjustsolutionsbutaccompanythemwithdetailedexplanationsaswell.Also,whereappropriateIhaveincludedreferencestoallsortsofdocumentation,oftenthemostrelevantspotintheBlenderPythonAPIdocs,justtosaveyoufromanendlesshuntfortherightinformation.Anindexoftermsisalsoprovided.

Page5

Page 7: Sample Blender Add-On Cookbook - michelanders.nl

Whoisthisbookfor?

Codeavailability

Information

Thisbookisforadd-ondeveloperswhowanttogoonestepfurtherandaddaprofessionaltouchtotheircreationsorwanttoaddfunctionalitythatisn'tsostraightforwardtoimplement.

YoushouldhaveagoodunderstandingofPythonandhavesomeknowledgeofwritingBlenderadd-onsalready.ThisisacookbookinthesensethatitprovidessmallpiecesofcodethatareaimedatsolvingaparticularproblembutifyouwantamoregeneralintroductionyoucouldconsidermybookCreatingadd-onsforBlender.

Thecodeinthebookispresentedascodesnippetsthatwillnotrunontheirown.Typicallyjusttheexecute()functionofanoperatorisshown.However,tospareyoutheeffortoftypingovermanylinesofcode,eachrecipereferstoafilethatyoucandownloadandthatimplementsasmallbutcompleteadd-onthatusesthecodeshowninthesnippet,soyoucantestitoutimmediately.

AllcodeexamplesarelicensedundertheGPLandavailablefromthisGitHubrepository:

https://github.com/varkenvarken/blenderaddon-cookbook.

Eachrecipecontainsindividualreferencestotherelevantcodebutyoucanalsodownloadallcodeaasingle.zipfilebyclickingonthe'Cloneordownload'buttonandselecting'Downloadas.zip':

AllcodeistestedagainstthelatestversionofBlender(2.78aattimeofwriting)

Page6

Page 8: Sample Blender Add-On Cookbook - michelanders.nl

Conventionsusedinthisbook

Pythoniccode

Abouttheauthor

Codesnippetsareshownasfollows

def·myfunction(x):

····y·=·x·*·x

····return·y

Functionorclassnamesusedintherunningtextareshowninbold:myfunction().

TherecipesinthisbookfocusonillustratingconceptsrelevanttowritingBlenderadd-ons.WedostrivetokeepthecodereadableandPythonicbutnotatallcosts.Sometimesthelimitationsinherentinformatingsourcecodeinbooksforceustosacrificetherecommendationinpep-8.Also,althoughweareawareofthedistinctions,weusethetermsfunctionandmethodinterchangeably.AndasforvaluespassedtofunctionswefollowtheKlingondefinition.

AlthoughaBlenderuserforovertenyears,IhavetoadmitthatIamanenthusiasticbut(very)mediocreartistatbest.IdiscoveredhoweverthatIreallyenjoyedhelpingpeopleoutwithprogrammingrelatedquestionsandacoupleofyearsagowhenPacktPublishingwaslookingforauthorsontheBlenderArtists/PythonforumIsteppedin.

Sofarthishasresultedinseveralbooksinprint:

Blender2.49Scripting,ISBN9781849510400,PublishedbyPacktPublishinginApril2010.

Python3WebDevelopment,ISBN9781849513746,PublishedbyPacktPublishinginMay2011.

RecentlyIswitchedtoselfpublishingandmythirdbook:'OpenShadingLanguageforBlender',distributedbySmashwords,majorretailersandBlenderMarket,wasthefirstresult.

Page7

Page 9: Sample Blender Add-On Cookbook - michelanders.nl

Mylatestbookiscalled'Creatingadd-onsforBlender'whichgivesabroaderandmoregentleintroductiontoBlenderadd-onsthanthisbook.

ImaintainablogonBlenderrelatedthings,'SmallBlenderThings'(blog.michelanders.nl)andIkeepaneyeonthecodingforumsathttp://www.blenderartists.org/forum/whereyoucanalsocontactmeviaprivatemessageifyoulike,mynicknamethereis'varkenvarken'.

IalsooffersomeBlenderadd-onsonBlenderMarket,thefirstonewascalledWeightLifter,avertexgrouptool,butnowaccompaniedbySpaceTreePro,aenvironmentawaretreemodeler,andIDMapper,atooltocreateID-mapsbasedonsmartheuristics.IfyoulikeyoucanhavealookatmyBlenderMarketstoretoseewhat'sonoffer.

IliveinasmallconvertedfarminthesoutheastoftheNetherlandswhereweraisegoatsforahobby.Wealsokeepafewchickensandthegeneralmanagementofthefarmislefttoourcats.Thisarrangementleavesmewithwithenoughtimetowritetheoccasionalbook.

Page8

Page 10: Sample Blender Add-On Cookbook - michelanders.nl

Intro

Explanation

Createapropertyselectiondropdown

Inmanysituationsyoumightwantyouroperatortolettheuserpicksomethingfromalistofchoices.IfthesechoicesrefertoBlenderitems,likeobjects,meshes,uv-maps,bones,modifiers,etc.wecanusetheprop_search()functionofalayoutobjecttotailorthedraw()functionofouroperatorinasinglelineofcode.Indoingsowenoonlycreateaneasytouselistofchoicesbutalsopreventtheuserfromthemistakesthatarepossiblewhenenteringachoicebyhand.

Inthisrecipewecreateasimpleoperatorthatletsyouselectanobjectandthatwillthenpositiontheactiveobjectrightnexttothischosenobjectonthex-axis.Theselectionboxthatletstheuserchooseanobjectispresentedwiththehelpoftheprop_search()function.

operatorproperties,prop_search,draw,bpy_props_collection,StringProperty

Whenyouuseaprop_search()functiontheresultoftheuserselectionneedstobestoredinaStringProperty

····other·=·StringProperty(name="Other·object")

Tocontrolthewaytheoperatorpropertiesaredisplayedweprovideanimplementationofthedraw()functioninouroperatorclass.Thestringpropertydoesn'tneedtobedisplayedbutthesearchwidgetitselfdoes

····def·draw(self,·context):

········layout·=·self.layout

Addingawidgetthatletstheuserselectanobjectoranythingelsefroma

Page51

Page 11: Sample Blender Add-On Cookbook - michelanders.nl

bpy_props_collectionisdonewiththeprop_search()function.Thisfunctiontakesareferencetothecurrentoperator,thenameoftheStringPropertytostoretheselectionin(inthiscase'other'),areferencetoanobjectandthenameofthebpy_props_collectiontolist.Inthiscasewewanttheusertoselectanobjectsoourbasisisbpy.dataandtheattributeweinterestedinisobjects

········layout.prop_search(self,'other',bpy.data,'objects')

Inthiscasethiswillresultinalistofobjectsthatwilldisplayedinadropdown.Theactualchoice(thenameofthechosenobject)willbestoredintheotherproperty.

ThisisaveryversatilewaytopresentchoicesbecausemanythingsinBlenderareofthetypebpy_props_collection.Forexampletopresenttheuserwithalistofuv-mapsfortheactivemeshobject,youcouldsimplywritelayout.prop_search(self,'uvmap',context.object.data,'uv_layers')assumingofcourseyouhaveaStringPropertydefinedinyouroperatorthatiscalled'uvmap'.

Nowwiththeselectionofanotherobjectavailable,theexecute()functioncanusethisinformationtoretrievetheactualchosenobject

····def·execute(self,·context):

········if·self.other·in·bpy.data.objects:

············other·=·bpy.data.objects[self.other]

Thefinalstepistoalterthelocationoftheactiveobjecttoputitrightbesidethechosenobject

Page52

Page 12: Sample Blender Add-On Cookbook - michelanders.nl

Keypoints

Code

Seealso

Refs

············ob·=·context.active_object

············ob.location·=·other.location

············ob.location.x·+=·1

········return·{"FINISHED"}

Youcanprovideadropdownselectionofanybpy_props_collectioninBlenderManycollectionsofitemsinBlenderareofthetypebpy_props_collectionincludingalltheitemsinbpy.dataandthingslikevertexgroupsoruv-mapsinobjectsAStringPropertyisneededtoholdtheresultoftheuserselectionTheprop_searchmethoudofaLayoutobjectwilltakecareofthepresentation

Ifyouinstallthisadd-onamenuitemObject→Propsearch examplewillbeaddedthe3d-viewinobjectmode.

GitHub:propsearch.py

Addingpersistentpropertiestoobjects

Propertycollectionsandthepropertyselectiondrop-down

https://docs.blender.org/api/blender_python_api_current/bpy.types.bpy_prop_collection.html

https://docs.blender.org/api/blender_python_api_current/bpy.types.UILayout.html?bpy.types.UILayout.prop_search#bpy.types.UILayout.prop_search

Page53

Page 13: Sample Blender Add-On Cookbook - michelanders.nl

Intro

Explanation

Createamodaloperator

Amodaloperatorisanoperatorthatkeepsonrunningafteritiscreated.Unlikeanon-modaloperatorthatperformssomespecificfunctionandthenterminates,amodaloperatorcankeeponinteractingwiththeuser.Examplesofmodaloperatorsarethegrab/moveandscaleoperators.

Toperformthisinteractionamodaloperatorshouldhaveamodal()methodthatiscalledeverytimeaneventoccurs.Examplesofeventsaremousemovementsorkeypressesbuttimerscanalsocreateeventsatfixedintervals.

Ifamodaloperatorisaddedtoamenuitstartsitsactivitywhentheinvoke()methodiscalledandtheoperatorisregisteredtoreceiveevents.

Inthissimplerecipewewillcreateamodaloperatorthatoncestarted,keepsonshowingeacheventintheareaheaderuntiltherightmousebuttonisclickedorthe Esc-keypressed.Thiswayyoucangetanideaofwhatkindofeventsyoumayactupon.

modaloperator,event

Theinvoke()functionofamodaloperatoriscalledwhensomeoneclicksamodaloperatorthathasbeenaddedtoamenu.Itcanperformanyinitializationactivitybutwhatreallymakesanoperatormodaliswhenitregistersitselfasamodalhandlerwiththewindowmanager.Thiswillcauseitsmodal()methodtobecalledeachtimesomeeventoccurs.Notethattheinvoke()methodisalsopassedanevent,whichmakesitpossibletobindamodaloperatortodifferentshortcutkeysforexampleandperformaninitializationbasedontheactualshortcutkeypressed,becausetheeventpassedtotheinvoke()methodisactuallythisfirstkeypressormouse-click

Page141

Page 14: Sample Blender Add-On Cookbook - michelanders.nl

Keypoints

····def·invoke(self,·context,·event):

········context.window_manager.modal_handler_add(self)

········return·{'RUNNING_MODAL'}

Onceregisteredasamodalhandlerthemodal()methodiscalledeachtimeaneventoccurs.Theeventargumentcontainsatypeandavalueandadditionalinformationbasedonthetype.Formouseeventsitwillalsohavethemousecoordinates.Herewedisplayafewrelevantattributesintheareaheadersoyoucanexperimenttoseewhatkindofvaluesareproducedbydifferentevents

····def·modal(self,·context,·event):

········context.area.header_text_set(

············"event:·{e.type}·{e.value}·({e.mouse_x},{e.mouse_y})"

························.format(e=event))

········context.area.tag_redraw()

Acommonconventionformodaloperatorsistocanceltheiractivityifeitherthe Esc-key ispressedortherightmousebuttonisclicked.Herewecheckforthisscenarioandresettheareaheaderbeforereturning{'CANCELLED'}tosignalwearedone.(Notethatthereturnvalueisasetwithasinglestring)

········if·event.type·in·{'RIGHTMOUSE',·'ESC'}:

············context.area.header_text_set()

············context.area.tag_redraw()

············return·{'CANCELLED'}

Forallothereventswejustkeeponrunning,somethingwesignalbyreturning{'RUNNING_MODAL'}

········return·{'RUNNING_MODAL'}

Inanotherrecipewewillseethatitisalsopossibletopassthroughsomeeventssothatotheroperatorsmayactonthem.

Page142

Page 15: Sample Blender Add-On Cookbook - michelanders.nl

Code

Seealso

Refs

AmodaloperatorinstallsamodalhandlerthatkeepsonactingaftertheinitialcallThisiscommonlythemodal()methodoftheoperatoritselfThismethodiscalledeverytimeaneventhappensEventscanbemouseactions,keypressesortimereventsAmodalhandlermayremoveitselfbyreturning{'CANCELED'}orkeeponrunningbyreturning{'RUNNING_MODAL'}

Thisadd-oninstallsamodalhandlerwhenyouclickonAdd→Mesh→Modal Operatorinthe3d-viewinobjectmode.

GitHub:modaloperator.py

Usingpassthroughinamodaloperator

Showhintsinanareaheader

MoreonthedifferencebetweentheOperatormethodspoll(),invoke(),execute(),draw()&modal()

http://blender.stackexchange.com/questions/19416/what-do-operator-methods

Page143

Page 16: Sample Blender Add-On Cookbook - michelanders.nl

Index

Aadd-ondistribution1

add-onpreferences1

animation1

area1

areaheader1

attributes1

Bbase1

beziersplines1

BMesh1,2

bpy_props_collection1

Ccursor1

curveobjects1

customdatalayer1

customproperty1

Cycles1,2

Ddraw1

drawhandler1

driver1

Page178

Page 17: Sample Blender Add-On Cookbook - michelanders.nl

Eedge1,2

EnumProperty1

event1

Fface1,2

foreach_get1

foreach_set1

frame1

Hhotkey1

Iicon1

intersection1

Kkd-tree1

keymap1

Llayers1

library1

loop1

Page179

Page 18: Sample Blender Add-On Cookbook - michelanders.nl

Mmaterial1

median1

menu1,2

Mesh1

modal1

modaloperator1,2,3,4,5

modifier1,2,3

module1

NNodeWrangler1

nodes1,2,3

numpy1

Oobject1

objectcoordinates1

objectparenting1

object_utils1

OpenGL1,2,3,4

operator1

operatorproperties1

Ppackage1

Panel1,2,3

parameterizedobject1

Page180

Page 19: Sample Blender Add-On Cookbook - michelanders.nl

parentingobjects1

particlesystem1,2

passthrough1

pixelvalue1

previewcollection1

progressbar1

prop_search1

property1

PropertyGroup1

pydriver1

Rray-casting1

region1

report()1

Sscene1

screen1

screencoordinates1,2

separator1

shader1

shortcut1

space1

StringProperty1,2

submenu1

subsurfacemodifier1

T

Page181

Page 20: Sample Blender Add-On Cookbook - michelanders.nl

thumbnail1

VVector1

vertex1,2

vertexgroup1

Wwindow1

windowmanager1

worldcoordinates1,2,3

worldmatrix1

Page182

Page 21: Sample Blender Add-On Cookbook - michelanders.nl

This is a sample of my book 

 

Blender Add-on Cookbook 

A cookbook with useful programming recipes for Blender add-ons 

 

If you like to buy a full copy, please visit my Blender Market store: 

https://blendermarket.com/creators/varkenvarken 

In the store you will also find a more gentle introduction to add-ons called  

Creating Add-ons for Blender, a practical primer.