Scripting tutorial and help on script writing

Started by mertmg, March 20, 2016, 11:44:00 AM

Previous topic - Next topic

0 Members and 1 Guest are viewing this topic.

mertmg

hi All,

i`m really in love with KS6.1 at the moment. it is so convenient for me to use it. when its needed i can stacked up my scenes and queue them or directly render them in the background. so now i`m trying to level up on KS6. i would like to use scripting on my next project which will kind of catalogue renderings for several parts i`ve designed. to be able to render them i would like to use scripting console as it can help me to automatise process. i don`t have background related with coding or scripting. but i can understand a bit of it as they are sensible. but i`m having difficulties to understand scripting on KS6 as there is not that much tutorials or webinars around. help page seems ok but not for starter without a great knowledge of scripting. so is there any plans or anywhere that i can find some more information and/or help regarding to scripting on KS6. it would be great if anyone can give a response within next couple days as i`m going to start my massive rendering job.

i would like to create several scripts to be able to keep each single bip file in same look. first of all i would need a setup script to which should be able to
*rotates the whole assembly
*drops to ground
*change environment and cancel ground shadows if needed
*rotates environment
*play with brightness and contrast
*changes image size to landscape or portrait A4 dimension
*creates  a new camera with a specific angle and  zoom fit all etc.
*applies material template or templates
*it would be great if we can set render option as desired. if not we can apply this one on next script.

after this setup script i`ll configure my labels and amend other materials manually and make some changes if necessary

next step will a rendering and/or queuing script which should be able to do below
*ask file name and folder
*if possible give a version to previous assigned name
*image size and camera selection
*advanced render options for samples&rays and shadows etc.
*if we can create an option to select created scenes it would be cherry on top.
*CPU usage selection
*add to queue or render in background

so if anyone can help on this one i`ll be over the moon. i`ve tried to write something last week but i couldn't achieve it. so i think if i can get some extra help i can crack on very well. and i`m pretty sure if we can write up this kind of script this can be used as a library script on KS7 as this one will be quite helpful for anyone.

Thanks you for all in advance.
i`ll be looking forward to see responses.

Thanks
MERT

mertmg

are there anyone? i tried to write down something but it fails. i can only get simple renders. i need help

mertmg

ok. i see. Keyshot  doesn`t have  enough people to help around here. i`ve spent whole day to create a simple code which wasnt easy for me. i made test and trial coding :)
and i try to collate everything under a script for start.

simply this script asks you below options

*lighting presets ( you can cancel this one or replace with other option or add some more with changing option names
*which Camera to use( if not selected uses Front Camera
*queue or not
*output folder
*file name in 3 steps ( you can reduce this to just one name option but i prefer this one for my run)
*output dimensions width & height
(note script has advanced render options. it would be better if you play with options. they are rough at the moment.
i also add alpha channel in advanced render options as well. I spent a bit time to make it work :)

That`s all I could achieve for now. I`ve tried to rotate my main part in my scene as i explained on my previous message. but it seems quite complicated i definitely help on that one. if there is anyone knows how to deal with rotating parts on your scene please help me!!!
I`m also after zooming whole image. I`m willing to create a camera which has an exact angle and zoom to main object in the scene.

# -*- coding: utf-8 -*-
# AUTHOR MERT GUNDOGDU
# VERSION 0.0.1
# Render customiser
import os

def main():
    values = [("Lighting", lux.DIALOG_ITEM, "Ligthing Preset:", lux.getLightingPreset(),
               lux.getLightingPresets()),
              ("cam", lux.DIALOG_ITEM, "Camera to use:", lux.getCamera(),
               lux.getCameras()),
              ("Queue", lux.DIALOG_CHECK, "Queue", False),
              ("folder", lux.DIALOG_FOLDER, "Output folder:", None),
              ("name", lux.DIALOG_TEXT, "Project code:", "COT"),
              ("modno", lux.DIALOG_TEXT, "Module No:", "0111"),             
              ("inst", lux.DIALOG_TEXT, "Instance No:", "10.png"),
              ("width", lux.DIALOG_INTEGER, "Output width:", 1200),
              ("height", lux.DIALOG_INTEGER, "Output height:", 800)]

    opts = lux.getInputDialog(title = "Render ",
                              desc = "Render scene",
                              values = values,
                              id = "rimtest.py")

    light = opts["Lighting"][1]
    cam = opts["cam"][1]
    que = opts["Queue"]

    if not opts: return

    if len(opts["folder"]) == 0:
        raise Exception("Folder cannot be empty!")

    if len(opts["name"]) == 0:
        raise Exception("Image name cannot be empty!")
   
    if len(opts["modno"]) == 0:
        raise Exception("Module No cannot be empty!")
 
    if len(opts["inst"]) == 0:
        raise Exception("Instance No cannot be empty!")

    oldcam = lux.getCamera()

    partname = opts["name"] + opts["modno"] + opts["inst"]
    path = os.path.join(opts["folder"], partname)
    width = opts["width"]
    height = opts["height"]

    lux.setLightingPreset(light)
    lux.setCamera(cam)

    ropts = lux.getRenderOptions()
    ropts.setAddToQueue(que)
    ropts.setOutputAlphaChannel(True)
    ropts.setThreads(22)
    ropts.setRayBounces(15)
    ropts.setMaxSamplesRendering(20)


    lux.renderImage(path = path, width = width, height = height, opts = ropts)

    # Reset to old camera.
    lux.setCamera(oldcam)

main()



fsong

Hi Mert,

Are you trying to rotate the camera or the part?

To rotate the part around the axis, you can see the reference about Matrix class in luxmath, using its functions.
    axis_x=luxmath.Vector(1, 0, 0)
    V = luxmath.Matrix().makeIdentity().rotateAroundAxis(axis_x, angle)
    node.applyTransform(V
)

To rotate the camera, you can see the reference in Lux. The camera direction and position need to be set at the same time. RenderPanoramicFrames script is a good example of setting the camera direction.

mertmg

Thanks for the reply.
Actually I would like to learn and try both. I've seen but couldn't understand exactly how it works on Panoramic Frames. But I will sort that one eventually.
So if we rotate the camera as you instructed can we zoom in to specific level. Such as let say I want to get a closer look at 200mm . I kind of get how can I rotate with testing it as you said but couldn't figure out zooming.

For part rotating I think I need to understand scenenodes which is seems complicated at the moment. Do you have any idea regarding to it?

fsong

Zoom in might be done by setting camera position.  But camera direction and position only take vectors. We need transfer polar coordinate(distance, azimuth, inclination) to Cartesian coordinate(x,y,z).  The R should be the distance. When zoomed in, R is reduced. then all x,y, z are changed accordingly as well.

I'm not totally clear about the scenenodes. You can get the root node and children node by getSceneTree(...) and getChildren(...). But you need to filter out the NODE_TYPE_GROUP. Cause each type has different attributes. I tend to use for loop to transform all children nodes. It should be some other ways to do this.

mertmg

Wow! It seems tricky. I'll throw something into script and give it a go probably it won't be easy  :o

Morten Kristensen

Hello mertmg,

Please do not send me PMs, thanks. We can't write all your scripts but can help if you have specific questions. :)

As I could deduce it seems you have read the API but you might benefit from reading the quick start: https://www.keyshot.com/scripting/doc/6.1/quickstart.html

Right now you have to do all camera work yourself by setting position, direction and up vectors. Another approach is to create cameras in KeyShot beforehand and then switch between them as you need.

As for rotation. You need to access the scene nodes to manipulate them. Take a look at tip #6 on the quick start page for more information on how to access scene nodes.

Thanks, hope that helps.

mertmg

Hi Morten ,
Of course i didn`t ask any one to write up a script just need help on writing on with more explanation. Basically I would like to get some help. i thought i can get more help rather than simple write up on help section. i`m not a script write but i managed to write up with checking existing scripts. but that`s all. i`m looking forward for more detailed script help. ithink it wont happening on KS6.
if you have any other script examples can you share it on the forum? when you see a script it helps a lot to understand what to do.

Niko Planke

Hello Mertmg,

The placement of the camera is all about the order for setting the values.
Starting with the direction and Twist, this should not be to complicated using Cosine ans Sine for the desired Azimuth and inclination angles. The same applies to  the upvector/Twist angle.

After the direction and up vector are set, you will need to set the zoom.
Setting the zoom/distance is a bit more complicated:

You will need to use a combination of:
getCameraDirection(...)
And
setCameraPosition(...)

The distance Value Is based on the Look At point/pivot, Camera position and Direction vector.
In this case i am assuming your look at point is (0,0,0)

The easiest way would be to use the direction vector to control the zoom.
Initially get the direction tuple and convert it to a vector:
directionvector=luxmath.Vector(lux.getCameraDirection())  #this creates a Vector for the direction.

To now move the Camera along the Direction-vectors line we can use multiples of it to position the camera.
distance=200
directionvector.mul(-distance)  #we need to swap the direction vector since it points in the wrong direction.

Now change it to a tuple and use it in lux.setCameraPosition(..)
lux.setCameraPosition(directionvector.mul(-distance).val())

Based on this you can now Control the "distance/zoom"

Setting the look at point using setCameraLookAt(...) afterwards should not impact the Camera distance and direction.

That workflow should enable you to position your camera as intended.

mertmg

Quote from: Niko Planke on March 29, 2016, 04:17:08 AM
Hello Mertmg,

The placement of the camera is all about the order for setting the values.
Starting with the direction and Twist, this should not be to complicated using Cosine ans Sine for the desired Azimuth and inclination angles. The same applies to  the upvector/Twist angle.
..........

thank you fro your detailed explanation Niko. i think this will help what i have to do. i`ve to find a way to spend more time on coding this will improve my workflow as i`m trying to edit each single file i`m working on now.

thank you very much. i`ll keep it updated when i can find a chance to try this.