Page 2 of 2 FirstFirst 12
Results 16 to 26 of 26

Thread: Code Snippets (aka: "How to...")

  1. #16
    Hey All,

    I do apologize for the necro-post, but this thread has been amazingly useful. I do have one question, though: I see you're using lwsdk.LWChannelInfo().channelEvaluate to ask a Channel what value it has. But I noticed in the documentation there's a ChannelAccess class that SEEMS to do that same job. Unfortunately I have not gotten that working. I was curious if a.) there was some benefit to using that class instead and b.) ...how exactly do you get that working? Passing a channelID doesn't seem to work.

    B
    Go TEAM VAD!! \/

  2. #17
    Red Mage Celshader's Avatar
    Join Date
    Feb 2003
    Location
    Burbank, California
    Posts
    1,817
    Quote Originally Posted by NanoGator View Post
    Hey All,

    I do apologize for the necro-post, but this thread has been amazingly useful. I do have one question, though: I see you're using lwsdk.LWChannelInfo().channelEvaluate to ask a Channel what value it has. But I noticed in the documentation there's a ChannelAccess class that SEEMS to do that same job. Unfortunately I have not gotten that working. I was curious if a.) there was some benefit to using that class instead and b.) ...how exactly do you get that working? Passing a channelID doesn't seem to work.

    B
    I hope skarloc answers, myself. I have not yet used channelEvaluate, but I have a script that at one point loops through the keys of a channel and replaces the original key values with "overscan" values. I am posting that code here in case it is of use.

    Code:
    """
    Clone Overscan Camera by Jennifer Hachigian
    2014-04-14
    With thanks to Deuce Bennett.
    
    Usage: select a camera in the scene and run this script to clone an
    overscan version of that camera.
    """
    
    import lwsdk
    
    def error(arg1, arg2):
        """ simplified way to call an error message. """
        lwsdk.LWMessageFuncs().error(arg1, arg2)
        
    def getZoomFactorEnvelope(item):
        """ returns the ZoomFactor envelope if it exists, and
        None if no ZoomFactor enveloper exists. """
        zEnv = None
        cGrp = lwsdk.LWItemInfo().chanGroup(item)
        chan = lwsdk.LWChannelInfo().nextChannel(cGrp, None)
        while chan:
            chanName = lwsdk.LWChannelInfo().channelName(chan)
            if chanName == "ZoomFactor":
                zEnv = chan
            chan = lwsdk.LWChannelInfo().nextChannel(cGrp, chan)
        return zEnv
    
    def overscanZoomFactorEnvelope(chan, overscan):
        """ applies overscan to every key in the ZoomFactor envelope. """
        env = lwsdk.LWChannelInfo().channelEnvelope(chan)
        key = lwsdk.LWEnvelopeFuncs().nextKey(env, None)
        while key:
            val = lwsdk.LWEnvelopeFuncs().keyGet(env, key, lwsdk.LWKEY_VALUE)
            old_zoom = val[1]
            new_zoom = val[1]/(overscan)
            lwsdk.LWEnvelopeFuncs().keySet(env, key, lwsdk.LWKEY_VALUE, new_zoom)
            key = lwsdk.LWEnvelopeFuncs().nextKey(env, key)
        
    
    def cloneOverscanCamera():
        """ clones a selected camera, adjusts its resolution/zoom,
        and renames it with the percentage of overscan involved. """
        items = lwsdk.LWInterfaceInfo().selected_items()
        if not items:
            error("No selected items.", "Please select an item.")
            return
    
        item = items[0]
        if lwsdk.LWItemInfo().type(item) != lwsdk.LWI_CAMERA:
            error("No selected camera.", "Please select a camera.")
            return
        
        zEnv = getZoomFactorEnvelope(item)
        
        curTime = lwsdk.LWInterfaceInfo().curTime
        name = lwsdk.LWItemInfo().name(item)
        w, h = lwsdk.LWCameraInfo().resolution(item)
        
        """ get overscan value from user """
        text = lwsdk.LWMessageFuncs().askName("Input new width.", "Width", str(w))
        try:
            overscan = float(text)/float(w)
        except ValueError:
            error("Wrong value.", "Enter a number next time!")
            return
        except TypeError:
            error("Cancelled.", "User cancelled operation.")
            return
        
        new_w = int( text )
        new_h = int( h * (overscan) )
        
        lwsdk.command("Clone 1")
        lwsdk.command("Rename %s_overscan_%d%%" % (name, (overscan-1.0) * 100))
        lwsdk.command("FrameSize %d %d" % (new_w, new_h))
        
        if zEnv:
            """ apply overscan to the ZoomFactor envelope """
            overscanZoomFactorEnvelope(zEnv, overscan)
        else:    
            """ apply overscan to the static ZoomFactor value """
            zoom = lwsdk.LWCameraInfo().zoomFactor(item, curTime)
            new_z = zoom/(overscan)
            lwsdk.command("ZoomFactor %f" % new_z)
        
    cloneOverscanCamera()
    Jen's 3D -- LightWave stuff.
    Jen's 2D -- my comic book.

    Python is my smashing board. LightWave is my S.M.A.K.

  3. #18
    I am just writing a houdini pfx reader/writer.
    The resulting python code could also be interesting for non-houdini users .. so I just wanted to share the houdini independant parts.

    Code:
    pfxDataFile = file('D:\\Root\\repositories\\tresuma\\source\\python\\common\\IO\\LW\\emitter.pfx')
    
    format_version, total_particles, total_frames = struct.unpack('>iii', pfxDataFile.read(12))
    print 'header', format_version, total_particles, total_frames
    for particle in range(0, total_particles):
        print 'current particle', particle
        start_frame, end_frame, life_frame = struct.unpack('>iii', pfxDataFile.read(12))
        print 'particle data', start_frame, end_frame, life_frame
        for position in range(start_frame, end_frame):
            xpos, ypos, zpos = struct.unpack('>fff', pfxDataFile.read(12))
            print 'particle pos', xpos, ypos, zpos
    
    pfxDataFile.close()
    this is the reader which atm just prints the data to the console.
    the writer contains a lot of hom code. so its not that interesting in this context
    Last edited by dulo; 05-20-2014 at 11:14 AM.
    martin dulovits
    technical director

    www.woogieworks.com

  4. #19
    Banned OnlineRender's Avatar
    Join Date
    Dec 2008
    Location
    Glasgow , Scotland , UK
    Posts
    6,359
    Thanks Jen ,brilliant thread ...

    just started to mess around with python & LW

    mainly >>> import urllib
    >>> urllib.urlretrieve('http://www.example.com/myfile.zip', 'path/to/download/dir/myfile.zip')

    essentially what I am doing is making a GUI with text fields/valuse that are assigned to download files * but lost lol
    Last edited by OnlineRender; 05-20-2014 at 12:03 PM.

  5. #20
    Little fix for read pfx python script
    Code:
    pfxDataFile = file('emitter.pfx')
    streamPos = pfxDataFile.tell()
    format_version, total_particles, total_frames = struct.unpack('>iii', pfxDataFile.read(12))
    print streamPos, 'header', format_version, total_particles, total_frames
    for particle in range(0, total_particles):
        streamPos = pfxDataFile.tell()
        print streamPos, 'current particle', particle
        start_frame, end_frame, life_frame, weight, resistance, size = struct.unpack('>iiifff', pfxDataFile.read(24))
        streamPos = pfxDataFile.tell()
        print streamPos, 'particle data', start_frame, end_frame, life_frame, weight, resistance, size
        for position in range(start_frame, end_frame + 1):
            streamPos = pfxDataFile.tell()
            xpos, ypos, zpos = struct.unpack('>fff', pfxDataFile.read(12))
            print streamPos, 'particle pos', xpos, ypos, zpos
    
    pfxDataFile.close()
    martin dulovits
    technical director

    www.woogieworks.com

  6. #21
    Quote Originally Posted by Celshader View Post
    I hope skarloc answers, myself. I have not yet used channelEvaluate, but I have a script that at one point loops through the keys of a channel and replaces the original key values with "overscan" values. I am posting that code here in case it is of use.

    Code:
    """
    Clone Overscan Camera by Jennifer Hachigian
    2014-04-14
    With thanks to Deuce Bennett.
    
    Usage: select a camera in the scene and run this script to clone an
    overscan version of that camera.
    """
    
    import lwsdk
    
    def error(arg1, arg2):
        """ simplified way to call an error message. """
        lwsdk.LWMessageFuncs().error(arg1, arg2)
        
    def getZoomFactorEnvelope(item):
        """ returns the ZoomFactor envelope if it exists, and
        None if no ZoomFactor enveloper exists. """
        zEnv = None
        cGrp = lwsdk.LWItemInfo().chanGroup(item)
        chan = lwsdk.LWChannelInfo().nextChannel(cGrp, None)
        while chan:
            chanName = lwsdk.LWChannelInfo().channelName(chan)
            if chanName == "ZoomFactor":
                zEnv = chan
            chan = lwsdk.LWChannelInfo().nextChannel(cGrp, chan)
        return zEnv
    
    def overscanZoomFactorEnvelope(chan, overscan):
        """ applies overscan to every key in the ZoomFactor envelope. """
        env = lwsdk.LWChannelInfo().channelEnvelope(chan)
        key = lwsdk.LWEnvelopeFuncs().nextKey(env, None)
        while key:
            val = lwsdk.LWEnvelopeFuncs().keyGet(env, key, lwsdk.LWKEY_VALUE)
            old_zoom = val[1]
            new_zoom = val[1]/(overscan)
            lwsdk.LWEnvelopeFuncs().keySet(env, key, lwsdk.LWKEY_VALUE, new_zoom)
            key = lwsdk.LWEnvelopeFuncs().nextKey(env, key)
        
    
    def cloneOverscanCamera():
        """ clones a selected camera, adjusts its resolution/zoom,
        and renames it with the percentage of overscan involved. """
        items = lwsdk.LWInterfaceInfo().selected_items()
        if not items:
            error("No selected items.", "Please select an item.")
            return
    
        item = items[0]
        if lwsdk.LWItemInfo().type(item) != lwsdk.LWI_CAMERA:
            error("No selected camera.", "Please select a camera.")
            return
        
        zEnv = getZoomFactorEnvelope(item)
        
        curTime = lwsdk.LWInterfaceInfo().curTime
        name = lwsdk.LWItemInfo().name(item)
        w, h = lwsdk.LWCameraInfo().resolution(item)
        
        """ get overscan value from user """
        text = lwsdk.LWMessageFuncs().askName("Input new width.", "Width", str(w))
        try:
            overscan = float(text)/float(w)
        except ValueError:
            error("Wrong value.", "Enter a number next time!")
            return
        except TypeError:
            error("Cancelled.", "User cancelled operation.")
            return
        
        new_w = int( text )
        new_h = int( h * (overscan) )
        
        lwsdk.command("Clone 1")
        lwsdk.command("Rename %s_overscan_%d%%" % (name, (overscan-1.0) * 100))
        lwsdk.command("FrameSize %d %d" % (new_w, new_h))
        
        if zEnv:
            """ apply overscan to the ZoomFactor envelope """
            overscanZoomFactorEnvelope(zEnv, overscan)
        else:    
            """ apply overscan to the static ZoomFactor value """
            zoom = lwsdk.LWCameraInfo().zoomFactor(item, curTime)
            new_z = zoom/(overscan)
            lwsdk.command("ZoomFactor %f" % new_z)
        
    cloneOverscanCamera()
    Thank you and thanks to everybody who is contributing code.. it has made my life lots easier, wanted you all to know it was worth your time.
    Go TEAM VAD!! \/

  7. #22
    When you load an image into the image list, can you get its resolution and ask it what color a specified pixel is?
    Go TEAM VAD!! \/

  8. #23
    Quote Originally Posted by NanoGator View Post
    When you load an image into the image list, can you get its resolution and ask it what color a specified pixel is?
    Yes. I don't have any basic code, but the "HDR to lights" script reads that information. You can look in the Lightwave specific portions of the code.

    http://clintons3d.com/plugins/lightwave/index.html

    The script is about half way down the page.

  9. #24
    "OH NO!", Joseph Joestar ncr100's Avatar
    Join Date
    Feb 2003
    Location
    San Francisco
    Posts
    1,100
    Blog Entries
    2
    May be OT: but has anyone thought about creating a github (or bitbucket) repository to collect these python utilities? We could spread the responsibility for vetting incoming changes / pull requests across a team of admins.

    I think of a utilities repository since these are not plugins but helper functions.

    I know LW 12 is supposed to provide a more extensive wrapper, perhaps making the "Lightwave Commands" first class Python citizens...but we don't have to wait for years for NewTek to upgrade their library via a major platform release. In fact that LW Command wrapping could be generated code...take each Command and make a def with the right # of params and steal some Python documentation from the SDK docs.
    -Nick
    audio: Ö ¤ wk Py

  10. #25
    Axes grinder- Dongle #99
    Join Date
    Jul 2003
    Location
    Seattle
    Posts
    14,726
    Just going to bump this thread, --I'm sure people have written other useful snippets since 7/29/2014. Please share, because this is one of the most useful threads in the forum.
    They only call it 'class warfare' when we fight back.
    Praise to Buddha! #resist
    Chard's Credo-"Documentation is PART of the Interface"
    Film the cops. Always FILM THE COPS. Use this app.

  11. #26
    Registered User Evil_Alan's Avatar
    Join Date
    Feb 2018
    Location
    USA
    Posts
    4

    Let's play with Skelegons!

    It's Valentine's Day. Lightwave needs some love!


    Python module needed:
    Transforms3d: https://matthew-brett.github.io/transforms3d/

    Optional:
    pynput: https://pythonhosted.org/pynput/keyboard.html
    pynput installation: https://www.youtube.com/watch?v=DTnz8wA6wpw

    Code:
    import numpy as np
    from transforms3d.euler import euler2mat, mat2euler
    from pynput.keyboard import Key, Controller
    from transforms3d.quaternions import quat2mat
    
    
    from lwsdk import ModCommand, Vector
    from lwsdk.pris.modeler import init, getpolygons, selpolygon, editbegin, editend
    
    if not init(ModCommand()):
    	raise Exception('Failed to initialize PRIS')
    
    keyboard = Controller()
    
    #SKLGNS = False
    SKLGNS = True
    
    
    
    
    '''
    skeleton = []
    for x in xrange(numBones):
    	boneData = bdata.read()
    	skeleton.append(boneData)
    '''
    
    
    allptID = []
    trans = []
    if SKLGNS == True:
    	c = -1
    	cs_options = lwsdk.marshall_dynavalues("1")  # set to layer with Skelegons
    	result = mod_command.execute(mod_command.data, cs_dict["SETLAYER"], cs_options, lwsdk.OPSEL_USER)
    	mesh_edit_op = mod_command.editBegin(0, 0, lwsdk.OPSEL_USER)
    	for bone in skeleton:
    		c += 1
    		BNps = (bone.posZ, bone.posY, bone.posX)
    		if bone.transformType == 1:
    			BNrt = (bone.rotW, bone.rotZ, bone.rotY, bone.rotX)
    			rt = quat2mat(BNrt)
    		else:
    			rt = euler2mat(bone.rotX, bone.rotY, bone.rotZ, axes='rzyx')
    		BNsc = (bone.scaleX, bone.scaleY, bone.scaleZ)
    		'''
    		BNsc = np.matrix(
    			[[bone.scaleX,               0,             0, 0], \
    			[0,                bone.scaleY,             0, 0], \
    			[0,                              0, bone.rotZ, 0], \
    			[0,                              0,             0, 1]]
    			)
    		'''
    		bnXM = np.matrix(
    			[[rt[0][0], rt[0][1], rt[0][2], 0], \
    			[ rt[1][0], rt[1][1], rt[1][2], 0], \
    			[ rt[2][0], rt[2][1], rt[2][2], 0], \
    			[  BNps[0],  BNps[1],  BNps[2], 1]]
    			)
    		#bnXM *= BNsc
    		trans.append(bnXM)
    		boneName = BoneNameArray[c]
    		BNparent = bone.parentID
    		
    		if BNparent != 0:
    			bnXM *= trans[BNparent]
    			pt = [bnXM[3,2], bnXM[3,1], bnXM[3,0]]
    		else:
    			pt = [bnXM[3,2], bnXM[3,1], bnXM[3,0]]
    		
    		
    		g = mesh_edit_op.addPoint(mesh_edit_op.state, pt)
    		allptID.append(g)
    		
    		
    		if BNparent != 0:
    			skelptID = []
    			skelptID.append(allptID[BNparent])
    			skelptID.append(allptID[-1])
    			
    			#                                         state,                   type,   template,    surf,       point_array
    			skel = mesh_edit_op.addPoly (mesh_edit_op.state,   lwsdk.LWPOLTYPE_BONE,       None,    "b_",          skelptID)
    	mesh_edit_op.done(mesh_edit_op.state, edit_op_result, 0)
    
    
    
    
    
    
    # Rename and set weightmaps
    	if not editbegin():
    		raise Exception('Failed to haze new guy.')
    	try:
    		polys = getpolygons()
    	except:
    		raise Exception('Call to getpolygons() got stuck in a corn field in Nebraska!')
    	if len(polys) == 0:
    		raise Exception('No polygons detected. Why you so stupid, stupid?!')
    	editend()
    	
    	p = lwsdk.LWStateQueryFuncs().mode(lwsdk.LWM_MODE_SELECTION)
    	print "\n"
    	print "MODE SELECTION is:\t " + str(p)
    	# 0:Point, 1:Polygon, 2:Volume, 3:Edge
    	
    	cs_test0 = mod_command.lookup(mod_command.data, "cmdseq")
    	if p == 1:
    		for x in xrange(len(polys)):
    			name = BnNmArray[x]
    			
    			lwsdk.pris.modeler.selmode(mode=1)
    			selpolygon('set', 'polyid', polys[x])
    			
    			cs_options0 = lwsdk.marshall_dynavalues(("SetTag", "PART "+name))
    			result0 = mod_command.execute(mod_command.data, cs_test0, cs_options0, lwsdk.OPSEL_USER)
    			
    			cs_options1 = lwsdk.marshall_dynavalues(("SetTag", "BONE "+name))
    			result1 = mod_command.execute(mod_command.data, cs_test0, cs_options1, lwsdk.OPSEL_USER)
    			
    			'''
    			not all bones have weightmaps:
    			root, bones for weapons stored in another file, rig controls, etc
    			so check with list that has the weightmap names
    			'''
    			if name in bw:
    				cs_options2 = lwsdk.marshall_dynavalues(("SkelegonSetWeight", name))
    				result1 = mod_command.execute(mod_command.data, cs_test0, cs_options2, lwsdk.OPSEL_USER)
    			
    			lwsdk.pris.modeler.selmode(mode=1)
    			selpolygon('clear', 'polyid', polys[x])
    	else:
    		raise Exception('Not in Polygon Mode - Skelegons not renamed')
    
    
    # Fit All
    keyboard.press('a')
    keyboard.release('a')
    
    '''
    # Fit Selected
    with keyboard.pressed(Key.shift):
    	keyboard.press('a')
    	keyboard.release('a')
    '''


Page 2 of 2 FirstFirst 12

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •