Páginas

Pequeno Guia Blender Python para Villares / GitHub

https://github.com/villares/material-aulas/issues/77

Olá!

Este é um pequeno guia introdutório para aqueles que desejam começar a entender um pouco da relação entre Blender 3D e Python.

O Blender 3D é um programa de computador gratuíto com diversos propósitos, sendo o principal a modelagem de superfícies tridimensionais. Além disso o Blender é um programa de código fonte aberto e livre, isso significa que podemos estudar como este programa foi escrito e participar desse processo de escrita se tivermos interesse, para contribuirmos com seu desenvolvimento. O Blender é mantido por uma vasta comunidade organizada a partir da internet e que tem como sede a Fundação Blender na Holanda.

Já Python é uma linguagem de programação mantida também por uma extensa comunidade online que trabalha de maneira transparente. A sede da Fundação Python fica nos Estados Unidos.

Uma parte do programa Blender foi e é escrita utilizando a linguagem Python. Quando falamos de Blender e Python existem diversas interconexões. A primeira delas que não podemos perder de vista é que são duas comunidades bastante dinâmicas e mutáveis em constante evolução no desenvolvimento de seus inúmeros produtos intelectuais. No entanto quando queremos obter um resultado mais pragmático, acabamos tendo de formar uma visão mais estática destes projetos por um instante, para alcançarmos, por exemplo, o objetivo de escrever um singelo guia como este.

O Blender, enquanto programa (ou aplicativo) de computador é distribuído com uma versão de Python. Isso significa que ao obtermos o Blender ele vem com uma versão do Python "empacotada" com ele, para usar mais um termo técnico. Note que este último trecho é uma forma de olharmos já mais encaixotada, direcionando este guia para uma didática baseada em instruções gráficas. Estamos nos afastando de algo bem amplo que são duas imensas comunidades humanas com inúmeros graus de interação entre si para nos dirigir a algo bem específico e bastante simples: como executar uma operação dentro do Blender utilizando o Python "que vem com o Blender".

Neste nosso pequeno percurso vamos então seguir os seguintes passos:
 

1) Entender como o Blender pode ser obtido e instalado.

2) Uma vez dentro do Blender observar em sua interface gráfica o local destinado a estabelecer um diálogo mais direto entre o Blender e o Python que vem instalado com ele e finalmente,

3) Criar uma pequena peça de código que executa uma operação que guarda relação com a modelagem 3D.
 

1) Como obter o Blender e instala-lo

O Blender é um programa de computador que pode ser obtido no endereço:

https://www.blender.org/  

Enquanto escrevo este guia a versão para download oferecida automaticamente na seção de downloads do blender.org é a 2.92.0

A fundação Blender mantém binários executáveis (também chamados simplesmente de programas ou aplicativos) que podem ser baixados para o seu computador para os seguintes sistemas operacionais: Windows, Linux e MacOS. Na aba downloads em blender.org já somos direcionados para o download do sistema operacional que utilizamos, caso estejamos realizando esta operação em um dos sistemas operacionais mencionados. Uma opção mais avançada para obtenção do programa é voce mesmo compilar o Blender ou então instala-lo pelo terminal no Linux. Por enquanto vamos nos ater a primeira opção que é obter o binário previamente compilado para o seu sistema operacional. Note que uma vez aberta a aba downloads, além da opção automática e do grande e irrestível botão de download, mais embaixo o Blender nos oferece "outras versões". (FIGURA A)


 Uma observação importante a ser feita a esta altura é que o Blender foi projetado para funcionar a partir da sua própria pasta, sem alterar o conteúdo de outras pastas no decorrer de sua instalação e execução. Esta última observação é de particular interesse para os usuários do Windows. Se ao invés de baixarmos o instalador optarmos pelo arquivo compactado, basta descompactar o arquivo baixado e clicar no executável Blender para que o mesmo funcione. Experimente fazer isso pelo aspecto didático! Caso você esteja tendo dificuldades para instalar e iniciar o Blender em seu computador por favor não desista. Existe um repositório de versões anteriores que também são excelentes em https://download.blender.org/release/, e além disso você pode entrar em contato com a comunidade Blender em um de seu diversos canais de comunicação para esclarecer dúvidas. Para saber mais visite e explore o endereço blender.org! :)

 

2) O Blender pode ser iniciado a partir do terminal (Linux e Mac) e pode deixar o prompt de comando visível no Windows. Estas janelas retornam informações importantes sobre a interação entre Blender e Python, então procure deixa-las acessíveis quando for iniciar sua exploração. Uma vez dentro da interface gráfica do Blender, no Windows, procure por Window --> Toggle System Console. No Linux e no Mac abra o terminal e inicie o Blender com ./blender depois de navegar até a pasta onde você deixou o Blender. (FIGURA B)

 

Uma vez que o Blender é iniciado existe um local na inteface gráfica voltado para desenvolvimento com Python que é uma aba chamada Scripting no canto superior esquerdo. (FIGURA C)

3) Observando a interface gráfica do Blender assim que o iniciamos, podemos notar que o mesmo vem com um cubo cinza com contorno laranja em seu arquivo padrão. Repare que no interior deste cubo há um ponto laranja. É a origem deste cubo. Vamos supor que queiramos desmontar este cubo obtendo seis faces, tendo cada uma destas faces a origem posta sobre seu centro de massa respectivo. O que irá ocorrer neste passo, de forma resumida, é que um objeto com seu centro de massa (cubo) será desmembrado em seis outros objetos, cada qual com seu próprio centro de massa (seis faces). Existem duas maneiras de obtermos este resultado: a primeira é via interface gráfica acessando uma série de comandos (Clica daqui, clica dali... Repete inúmeras vezes...). A segunda maneira é automatizar este processo utilizando um script python que acessa um módulo do Blender chamado bpy. Neste pequeno guia vamos utilizar esta segunda maneira. O primeiro passo, depois de iniciado o Blender, é acessar a tab "Scripting" que mencionamos acima. Depois, no editor de texto, criamos um novo texto e colocamos o seguinte script:

import bpy
bpy.ops.object.mode_set(mode = 'EDIT')
bpy.ops.mesh.select_all(action='SELECT')
bpy.ops.mesh.edge_split()
bpy.ops.mesh.separate(type='LOOSE')
bpy.ops.object.mode_set(mode = 'OBJECT')
bpy.ops.object.origin_set(type='ORIGIN_GEOMETRY')

Agora é só rodar o script apertando a flexinha Run Script.


(FIGURA D)

Você irá notar que agora temos seis pontos sobre cada uma das faces, ao invés de apenas uma. Significa que agora temos seis objetos ao invés de um só. Repare no outliner que cada um desses objetos herdou o nome do objeto inicial (cubo) então terminamos com seis objetos com o nome de cubo, mas eles são na verdade agora faces, é só que o Blender não entende este nuance na hora de criar o nome destes novos objetos.

Algumas outras coisas interessantes aconteceram também: Há um campo com informações sobre os comandos que foram executados por exemplo.

(FIGURA E)

Mas de volta ao script. O que será que cada uma das linhas está nos dizendo?

import bpy
bpy.ops.object.mode_set(mode = 'EDIT')
bpy.ops.mesh.select_all(action='SELECT')
bpy.ops.mesh.edge_split()
bpy.ops.mesh.separate(type='LOOSE')
bpy.ops.object.mode_set(mode = 'OBJECT')
bpy.ops.object.origin_set(type='ORIGIN_GEOMETRY')

A primeira linha importa o módulo bpy, que contém as operações que nos interessam. As demais linhas procedem com as operações necessárias para que o resultado seja alcançado. De forma resumida da segunda linha em diante é o que faríamos acessando a interface gráfica a partir de botões e menus, mas aqui está tudo condensado em um texto.

Um exercício interessante que pode ser feito para entendermos melhor estes diferentes painéis na interface gráfica é dar undo até o momento em que o cubo ainda não estava desfeito remover a primeira  linha do script onde está escrito import bpy e tentar rodar o script de novo. Você vai notar que o script não funciona o painel info aponta a falha, pedindo que olhemos o system console (Terminal ou prompt de comando). Lá deve aparecer escrito o seguinte: line 1, in <module> NameError: name 'bpy' is not defined.

(FIGURA F)

Veja que curioso no entanto: O Blender possui o Python Console. Caso retornemos ao estágio em que o cubo ainda não estava desfeito (podemos usar o undo novamente para isso) e copiarmos e colarmos o script lá (no Python console) sem a linha do import bpy e apertarmos enter, a operação vai funcionar, isso porque o módulo bpy já está carregado neste painel, não havendo a necessidade de invocá-lo.

(FIGURA G)

 

E para finalizar: como este script foi escrito? Se você copiar e colar a segunda linha do script bpy.ops.object.mode_set(mode = 'EDIT') em um buscador da internet um dos resultados de busca deve te redirecionar para a API (application programming interface) do Blender: https://docs.blender.org/api/current/bpy.ops.object.html onde está documentado como cada parte do Blender pode ser acessada (e eventualmente modificada, expandida) via texto. Além disso nós poderiamos copiar e colar os operadores utilizando Ctrl-C sobre qualquer item de um menu e depois passá-lo para o seu script.

(FIGURA H)

 

Há mais dicas de como acessar cada parte do Blender via código neste endereço: https://docs.blender.org/api/current/info_tips_and_tricks.html

Bem então por enquanto é isso. Espero que está pequenina exploração pelo vasto universo Blender/Python tenha sido agradável e eventualmente útil.

Um ótimo passeio para você pelo mundo do Python e do Blender!

Dentro da API do Blender outro lugar bacana para você continuar a sua jornada Blender + Python: https://docs.blender.org/api/current/info_quickstart.html

Há também uma live de Python do Eduardo Medeiros que também trabalha muitos dos conteúdos que tratamos aqui:


 

 

https://github.com/villares/material-aulas/issues/77

Hello! 

This is a short introductory guide for those who want to start to study a little about the relationship between Blender 3D and Python. Blender 3D is a free computer program with several purposes, the main one being the modeling of three-dimensional surfaces. Furthermore, Blender is an open source and free program, this means that we can study how this program was written and participate in this writing process of it (if we are interested), or to contribute to its development. Blender is maintained by a vast community organized from the internet and has its headquarters in the Blender Foundation in the Netherlands.

Python, on the other hand, is a programming language maintained also by an extensive online community that works transparently. The headquarters of the Python Foundation is in the United States.

 
There is large part of the Blender 3D program was and is written using the Python language. When we talk about Blender and Python there are several interconnections. The first one that we must not lose sight of is that they are both two very dynamic and changing communities in constant evolution in the development of their numerous intellectual products. However, when we want to obtain a more pragmatic result, we end up having to form a more static view of these projects for an instant, in order to achieve, for example, the objective of writing a simple guide like this.

Blender, as a computer program (or application) is distributed with a version of Python. This means that when we get Blender it comes with a version of Python "packaged" with it, to use yet another technical term. Note that this last section is a way of looking at it in a way that is more limitaded, directing this guide to a didactic based on graphic instructions. We are moving away from something very broad, which are two immense human communities with numerous degrees of interaction with each other, to address something very specific and quite simple: how to perform an operation within Blender using Python "that comes with Blender".

In our short journey, we will then follow the following steps: 1) Understand how Blender can be obtained and installed. 2) Once inside Blender, observe in its graphical interface the place destined to establish a more direct dialogue between Blender and Python that comes installed with it and finally, 3) Create a small piece of code that performs an operation that is related to 3D modeling.
 

1) How to obtain Blender and install it 

Blender is a computer program that can be obtained from: 

https://www.blender.org/ As I write this guide the download version offered automatically in the downloads section of blender.org is 2.92.0 

The Blender Foundation maintains executable binaries (also simply called programs or applications) that can be downloaded to your computer for the following operating systems: Windows, Linux and MacOS. In the downloads tab at blender.org we are automatically directed to download the version for the operating system we use, if we are performing this operation on one of the operating systems mentioned. A more advanced option for obtaining the program is to compile Blender yourself or install it through the terminal on Linux. For now we will stick to the first option which is to obtain the binary previously compiled for your operating system. Note that once the downloads tab is open, in addition to the automatic option and the large and sexy download button, Blender offers us "other versions" below. (FIGURE A)


An important note to be made at this point is that Blender was designed to work from its own folder, without changing the contents of other folders during installation and execution. This last observation is of particular interest to Windows users. If instead of downloading the installer we choose the compressed file, just unzip the downloaded file and click on the Blender executable for it to work. Try it for the didactic aspect! If you are having trouble installing and starting Blender on your computer please do not give up. There is a repository of previous versions that are also excellent at https://download.blender.org/release/, and in addition you can contact the Blender community in one of its various communication channels to answer questions. To learn more visit and explore blender.org! :)

 

2) Blender can be started from the terminal (Linux and Mac) and can make the command prompt visible on Windows. These windows return important information about the interaction between Blender and Python, so try to make them accessible when you start your exploration. Once inside the Blender graphical interface, on Windows, look for Window --> Toggle System Console. On Linux and Mac open the terminal and start Blender with ./blender after navigating to the folder where you left Blender. (FIGURE B)

 

Once Blender is started there is a place in the graphical interface for development with Python that is a tab called Scripting in the upper left corner. (FIGURE C)

3) Looking at the Blender graphical interface as soon as we started it, we can see that it comes with a gray cube with an orange outline in its standard file. Notice that inside this cube there is an orange dot. It is the origin of this cube. Let's suppose that we want to dismantle this cube to obtain six faces, each of this faces with the origin placed on its respective center of mass. What will happen in this step, in summary, is that an object with its center of mass (cube) will be broken down into six other objects, each with its own center of mass (six faces). There are two ways to obtain this result: the first is via a graphical interface accessing a series of commands (Click here, click there... Repeat numerous times...). The second way is to automate this process using a python script that accesses a Blender module called bpy. In this small guide we will use this second way. The first step, after starting Blender, is to access the "Scripting" tab that we mentioned above. Then, in the text editor, we create a new text and put the following script:

import bpy
bpy.ops.object.mode_set(mode = 'EDIT')
bpy.ops.mesh.select_all(action='SELECT')
bpy.ops.mesh.edge_split()
bpy.ops.mesh.separate(type='LOOSE')
bpy.ops.object.mode_set(mode = 'OBJECT')
bpy.ops.object.origin_set(type='ORIGIN_GEOMETRY')

Now just run the script by pressing the Run Script arrow. (FIGURE D)

 

You will notice that we now have six points on each of the faces, instead of just one. It means that we now have six objects instead of just one. Notice in the outliner that each of these objects inherited the name of the initial object (cube) so we ended up with six objects named cube, but they are actually now faces, it's just that Blender doesn't understand this detail when creating the name of these new objects. Some other interesting things happened as well: There is a field with information about the commands that were executed for example. (FIGURE E)

But back to the script. What is it that each of the lines is telling us?

import bpy
bpy.ops.object.mode_set(mode = 'EDIT')
bpy.ops.mesh.select_all(action='SELECT')
bpy.ops.mesh.edge_split()
bpy.ops.mesh.separate(type='LOOSE')
bpy.ops.object.mode_set(mode = 'OBJECT')
bpy.ops.object.origin_set(type='ORIGIN_GEOMETRY')

The first line imports the bpy module, which contains the operations that interest us. The other lines proceed with the operations necessary for the result to be achieved. In a summarized form from the second line onwards is what we would do by accessing the graphical interface from buttons and menus, but here everything is condensed into a text.  

An interesting exercise that can be done to better understand these different panels in the graphical interface is to give undo until the moment when the cube was not yet undone into faces remove the first line of the script where it says import bpy and try to run the script again. You will notice that the script does not work. The info panel points out the fault, asking us to look at the system console (Terminal or command prompt). The following should appear there: line 1, in <module> NameError: name 'bpy' is not defined. (FIGURE F)

See how interesting: Blender has his own the Python Console. If we return to the stage where the cube was not yet undone (we can use undo again for that) and copy and paste the script there (in the Python console) without the import bpy line and press enter, the operation will work, because the bpy module is already loaded on this panel, so there is no need to invoke it. 

 (FIGURE G)

 

And finally, how was this script written? If you copy and paste the second line of the bpy.ops.object.mode_set script (mode = 'EDIT') into an internet search engine one of the search results should redirect you to the Blender API (application programming interface): https: //docs.blender.org/api/current/bpy.ops.object.html where it is documented how each part of Blender can be accessed (and eventually modified, expanded) via text. In addition we could copy and paste the operators using Ctrl-C over any item in a menu and then pass it into your script. 

 (FIGURE H)

 

There are more tips on how to access each part of Blender via code at this address: https://docs.blender.org/api/current/info_tips_and_tricks.html  

Well then, that's it for now. 

I hope this little exploration of the vast Blender / Python universe has been enjoyable and eventually useful. 

A great tour for you through the world of Python and Blender! Inside the Blender API, another nice place for you to continue your Blender + Python journey:  https://docs.blender.org/api/current/info_quickstart.html

 There is also a live by Eduardo Medeiros that can be found here that talks about this topic, but it is in portuguese: