analitics

Pages

Friday, June 30, 2017

Blender 3D - bpy and scripting - part 001.

The tutorial for today is bpy python module used by Blender 3D software for scripting.
The last Application Programming Interface (A.P.I.) for Blender 3D can be found here.
You need to take a look at the link to see the base of this python module.
The example I will start today is a python script that helps me to deal with Blender 3D.
First I put the script named catafest.py into Blender 3D path: C:\Program Files\Blender Foundation\Blender\2.78\python\lib.
The reason is to be load by Blender 3D application.
Let's start with the script:
First, you need to import the Blender 3D python module named bpy.
This allows us to deal with Blender 3D using python and Application Programming Interface (A.P.I.).
The script is an example not a lib script for Blender 3D.
The goal of this script is to show how to deal with python scripting into Blender 3D.
If you want to make a lib for the Blender 3D then you need to read about Python’s standard library - here.
My script just creates materials. To do that I used functions to make materials - mat, set the material to the object - set_mat and the run function to see how is working.
Let's see the python script:
import bpy

def mat(name,df_col,df_sh,df_int,sp_col,sp_sh,sp_int,alp,amb):
    mat = bpy.data.materials.new(name)
    mat.diffuse_color = df_col
    mat.diffuse_shader = df_sh
    mat.diffuse_intensity = df_int
    mat.specular_color = sp_col
    mat.specular_shader = sp_sh
    mat.specular_intensity = sp_int
    mat.alpha = alp
    mat.ambient = amb
    return mat

def set_mat(ob, mat):
    me = ob.data
    me.materials.append(mat)

def run(origin):
    # create two materials
    red = mat('Red', (1,0,0),'LAMBERT',1.0,(1,1,1),'COOKTORR',0.5, 1,1)
    blue = mat('Green', (0,1,0),'LAMBERT',1.0,(0,0.5,0.5),'COOKTORR',0.5, 1, 0.5)

    # create red cube
    bpy.ops.mesh.primitive_cube_add(location=origin)
    set_mat(bpy.context.object, red)
    # create a green torus
    bpy.ops.mesh.primitive_torus_add(location=origin)
    bpy.ops.transform.translate(value=(1,0,0))
    set_mat(bpy.context.object, blue)

if __name__ == "__main__":
    run((0,0,0))
To run this script put the script into the lib path of Blender 3D software.
Open the Blender 3D and go to the scripting area:

Now about the source code of this script.
As you know the Blender 3D interface let you add and change objects and materials.
Each material comes with a name, colors with a diffuse and specular property, alpha color, ambient color, etc. see the documentation.
Some values come like strings and can get it from Blender 3D interface, see:
diffuse_shader 

and the
specular_shader
.
The set_mat function just load one object using: me = ob.data
Then put the material to object using append function.
The run function is used to show the result with how to make materials, create objects with this materials.
I run into Blender 3D - Console area:
YTHON INTERACTIVE CONSOLE 3.5.2 (default, Dec  1 2016, 20:58:16) [MSC v.1800 64 bit (AMD64)]

Command History:     Up/Down Arrow
Cursor:              Left/Right Home/End
Remove:              Backspace/Delete
Execute:             Enter
Autocomplete:        Ctrl-Space
Zoom:                Ctrl +/-, Ctrl-Wheel
Builtin Modules:     bpy, bpy.data, bpy.ops, bpy.props, bpy.types, bpy.context, bpy.utils, bgl, blf, mathutils
Convenience Imports: from mathutils import *; from math import *
Convenience Variables: C = bpy.context, D = bpy.data

>>> import catafest 
>>> dir(catafest)
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__',
 'bpy', 'mat', 'run', 'set_mat']

>>> catafest.run((0,0,0))
This is the result of the script:





Wednesday, June 28, 2017

The Google API Client Library python module.

This python module named Google API Client Library for Python is a client library for accessing the Plus, Moderator, and many other Google APIs, according to the official link.
C:\Python27\Scripts>pip install --upgrade google-api-python-client
Collecting google-api-python-client
  Downloading google_api_python_client-1.6.2-py2.py3-none-any.whl (52kB)
    100% |################################| 61kB 426kB/s
...
Successfully installed google-api-python-client-1.6.2 ...
The example I used is this:
from oauth2client.client import flow_from_clientsecrets
import httplib2
import apiclient
from apiclient.discovery import build
from oauth2client.file import Storage
import webbrowser

def get_credentials():
    scope = 'https://www.googleapis.com/auth/blogger'
    flow = flow_from_clientsecrets(
        'client_id.json', scope,
        redirect_uri='urn:ietf:wg:oauth:2.0:oob')
    storage = Storage('credentials.dat')
    credentials = storage.get()

    if  not credentials or credentials.invalid:
        auth_uri = flow.step1_get_authorize_url()
        webbrowser.open(auth_uri)
        auth_code = raw_input('Enter the auth code: ')
        credentials = flow.step2_exchange(auth_code)
        storage.put(credentials)
    return credentials

def get_service():
    """Returns an authorised blogger api service."""
    credentials = get_credentials()
    http = httplib2.Http()
    http = credentials.authorize(http)
    service = apiclient.discovery.build('blogger', 'v3', http=http)
    return service

if __name__ == '__main__':
    served = get_service()
    print dir(served.blogs)
    users = served.users()

    # Retrieve this user's profile information
    thisuser = users.get(userId='self').execute()
    print('This user\'s display name is: %s' % thisuser['displayName'].encode('utf-8'))

    blogs = served.blogs()

    # Retrieve the list of Blogs this user has write privileges on
    thisusersblogs = blogs.listByUser(userId='self').execute()
    for blog in thisusersblogs['items']:
        print('The blog named \'%s\' is at: %s' % (blog['name'], blog['url']))
The result of this script is this:
C:\Python27>python.exe google_001.py
['__call__', '__class__', '__cmp__', '__delattr__', '__doc__', '__format__', '__func__', 
'__get__', '__getattribute__', '__hash__', '__init__', '__is_resource__', '__new__', 
'__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__sizeof__', 
'__str__', '__subclasshook__', 'im_class', 'im_func', 'im_self']
This user's display name is: Cătălin George Feștilă
The blog named 'python-catalin' is at: http://python-catalin.blogspot.com/
The blog named 'graphics' is at: http://graphic-3d.blogspot.com/
The blog named 'About me and my life ...' is at: http://catalin-festila.blogspot.com/
The blog named 'pygame-catalin' is at: http://pygame-catalin.blogspot.com/
About google settings then you need to have a google account to use Google’s API.
The first step for accessing the Google Developer’s Console.
Then navigate to the Developer Console’s projects page and create a new project for our application by clicking the Create project button and then enable blogger API.
Enter your projects name and hit create.
Click the Go to Credentials button with these settings like in the next image:

Download this credential information in JSON format, in this case, is the client_id.json file.
When you run for the first time this script you will see an open HTML page with your auth code.
The script example named google_001.py will come with this message:
C:\Python27>python.exe google_001.py
C:\Python27\lib\site-packages\oauth2client\_helpers.py:255: UserWarning: Cannot access credentials.dat: No such file or directory
  warnings.warn(_MISSING_FILE_MESSAGE.format(filename))
Enter the auth code:
Put this auth code and allow the script using the open page and your google account using Allow button.
Now you can run the example.