Work Specific Scripts
Jump to navigation
Jump to search
Rez speed Test
This feels nasty.
A python loop that starts houdini with rez, env by env, to see which library is slowing the start of Houdini's launch.
import subprocess import time b=subprocess.check_output(['rez', 'view', 'studio_launcher-houdini_prod_19.5']) #yeah i should probably call a rez module in python but youknow.... b=str(b).split('\\n- ')[1:] b=[x.split('\\r')[0] for x in b] # close.py: # import hou # hou.exit(exit_code=0, suppress_save_prompt=True) for rezenv in b[1:]: timeStarted = time.time() cmdflags = 'env '+b[0]+' '+rezenv+' -- houdini waitforui close.py' subprocess.call('rez '+cmdflags,shell=True,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL) timeDelta = time.time() - timeStarted print(rezenv+': '+str( f'{timeDelta:.1f}')+"s")
Returns:
octaneRender-h_19.5.368_2022.1.0.3: 15.7s redacted-0.1.1: 10.9s redacted-0.3.7: 11.4s redacted-0.1.4: 10.9s axiom-3.0.120: 29.6s QLib-0.2.80: 11.1s SideFXLabs-19.5.368: 77.0s MOPS-1.7.1: 11.8s deadline-10.2.0.10: 11.6s [Finished in 190.5s]
Shotgrid / Shotgun 101
tbd! tank.platform.engine.current_engine().context
pointcloud cleaning
import re, hou, glob def outputSequenceStartEnd(fileparm): '''given a file parm return the beginning and end of sequence''' parmval = fileparm.rawValue() matchObj = re.match( r'^(.*)\$F(\d*)(.*)', parmval, re.M|re.I) before = matchObj.groups()[0] extension = matchObj.groups()[2] fileGlob = before + '*' + extension files = glob.glob(fileGlob) files = sorted(files) #eww startframe = files[0].split(before[-6:])[-1].split(extension)[0] endframe = files[-1].split(before[-6:])[-1].split(extension)[0] return [startframe,endframe] for read in hou.selectedItems(): p = read.parm('file') read.setDisplayFlag(False) seq = outputSequenceStartEnd(p) ts = read.parent().createNode('timeshift') ts.setInput(0,read) ts.moveToGoodPosition() ts.parm('frame').setExpression('$F+'+str(seq[0]),replace_expression=True) hou_parent = read.parent() #autoCode # Code for /obj/file1/delete1 hou_node = hou_parent.createNode("delete", "delete1", run_init_scripts=False, load_contents=True, exact_type_name=True) # Code for /obj/file1/delete1/negate parm hou_parm = hou_node.parm("negate") hou_parm.deleteAllKeyframes() hou_parm.set("keep") # Code for /obj/file1/delete1/entity parm hou_parm = hou_node.parm("entity") hou_parm.deleteAllKeyframes() hou_parm.set("point") # Code for /obj/file1/delete1/stdswitcher1 parm hou_parm = hou_node.parm("stdswitcher1") hou_parm.deleteAllKeyframes() hou_parm.set(1) # Code for /obj/file1/delete1/affectnumber parm hou_parm = hou_node.parm("affectnumber") hou_parm.deleteAllKeyframes() hou_parm.set(0) # Code for /obj/file1/delete1/affectvolume parm hou_parm = hou_node.parm("affectvolume") hou_parm.deleteAllKeyframes() hou_parm.set(1) # Code for /obj/file1/delete1/size parm tuple hou_parm_tuple = hou_node.parmTuple("size") hou_parm_tuple.deleteAllKeyframes() hou_parm_tuple.set((0.5, 0.5, 0.5)) # Code for first keyframe. # Code for keyframe. hou_keyframe = hou.Keyframe() hou_keyframe.setTime(0) hou_keyframe.setExpression("bbox(0,6)+.5", hou.exprLanguage.Hscript) hou_parm_tuple[0].setKeyframe(hou_keyframe) # Code for last keyframe. # Code for keyframe. hou_keyframe = hou.Keyframe() hou_keyframe.setTime(0) hou_keyframe.setExpression("bbox(0,6)+.5", hou.exprLanguage.Hscript) hou_parm_tuple[0].setKeyframe(hou_keyframe) # Code for keyframe. hou_keyframe = hou.Keyframe() hou_keyframe.setTime(0) hou_keyframe.setExpression("bbox(0,6)+.5", hou.exprLanguage.Hscript) hou_parm_tuple[0].setKeyframe(hou_keyframe) # Code for first keyframe. # Code for keyframe. hou_keyframe = hou.Keyframe() hou_keyframe.setTime(0) hou_keyframe.setExpression("bbox(0,7)+.5", hou.exprLanguage.Hscript) hou_parm_tuple[1].setKeyframe(hou_keyframe) # Code for last keyframe. # Code for keyframe. hou_keyframe = hou.Keyframe() hou_keyframe.setTime(0) hou_keyframe.setExpression("bbox(0,7)+.5", hou.exprLanguage.Hscript) hou_parm_tuple[1].setKeyframe(hou_keyframe) # Code for keyframe. hou_keyframe = hou.Keyframe() hou_keyframe.setTime(0) hou_keyframe.setExpression("bbox(0,7)+.5", hou.exprLanguage.Hscript) hou_parm_tuple[1].setKeyframe(hou_keyframe) # Code for first keyframe. # Code for keyframe. hou_keyframe = hou.Keyframe() hou_keyframe.setTime(0) hou_keyframe.setExpression("bbox(0,8)+.5", hou.exprLanguage.Hscript) hou_parm_tuple[2].setKeyframe(hou_keyframe) # Code for last keyframe. # Code for keyframe. hou_keyframe = hou.Keyframe() hou_keyframe.setTime(0) hou_keyframe.setExpression("bbox(0,8)+.5", hou.exprLanguage.Hscript) hou_parm_tuple[2].setKeyframe(hou_keyframe) # Code for keyframe. hou_keyframe = hou.Keyframe() hou_keyframe.setTime(0) hou_keyframe.setExpression("bbox(0,8)+.5", hou.exprLanguage.Hscript) hou_parm_tuple[2].setKeyframe(hou_keyframe) # Code for /obj/file1/delete1/t parm tuple hou_parm_tuple = hou_node.parmTuple("t") hou_parm_tuple.deleteAllKeyframes() hou_parm_tuple.set((0, 0, 0)) # Code for first keyframe. # Code for keyframe. hou_keyframe = hou.Keyframe() hou_keyframe.setTime(0) hou_keyframe.setExpression("centroid(0,0)", hou.exprLanguage.Hscript) hou_parm_tuple[0].setKeyframe(hou_keyframe) # Code for last keyframe. # Code for keyframe. hou_keyframe = hou.Keyframe() hou_keyframe.setTime(0) hou_keyframe.setExpression("centroid(0,0)", hou.exprLanguage.Hscript) hou_parm_tuple[0].setKeyframe(hou_keyframe) # Code for keyframe. hou_keyframe = hou.Keyframe() hou_keyframe.setTime(0) hou_keyframe.setExpression("centroid(0,0)", hou.exprLanguage.Hscript) hou_parm_tuple[0].setKeyframe(hou_keyframe) # Code for first keyframe. # Code for keyframe. hou_keyframe = hou.Keyframe() hou_keyframe.setTime(0) hou_keyframe.setExpression("centroid(0,1)", hou.exprLanguage.Hscript) hou_parm_tuple[1].setKeyframe(hou_keyframe) # Code for last keyframe. # Code for keyframe. hou_keyframe = hou.Keyframe() hou_keyframe.setTime(0) hou_keyframe.setExpression("centroid(0,1)", hou.exprLanguage.Hscript) hou_parm_tuple[1].setKeyframe(hou_keyframe) # Code for keyframe. hou_keyframe = hou.Keyframe() hou_keyframe.setTime(0) hou_keyframe.setExpression("centroid(0,1)", hou.exprLanguage.Hscript) hou_parm_tuple[1].setKeyframe(hou_keyframe) # Code for first keyframe. # Code for keyframe. hou_keyframe = hou.Keyframe() hou_keyframe.setTime(0) hou_keyframe.setExpression("centroid(0,2)", hou.exprLanguage.Hscript) hou_parm_tuple[2].setKeyframe(hou_keyframe) # Code for last keyframe. # Code for keyframe. hou_keyframe = hou.Keyframe() hou_keyframe.setTime(0) hou_keyframe.setExpression("centroid(0,2)", hou.exprLanguage.Hscript) hou_parm_tuple[2].setKeyframe(hou_keyframe) # Code for keyframe. hou_keyframe = hou.Keyframe() hou_keyframe.setTime(0) hou_keyframe.setExpression("centroid(0,2)", hou.exprLanguage.Hscript) hou_parm_tuple[2].setKeyframe(hou_keyframe) hou_node.setExpressionLanguage(hou.exprLanguage.Hscript) hou_node.setInput(0, ts, 0) hou_node.moveToGoodPosition() hou_node.setDisplayFlag(True) hou_node.setSelected(True) delNode = hou_node hou_node = read.parent().createNode('rop_geometry') hou_parm = hou_node.parm("trange") hou_parm.deleteAllKeyframes() hou_parm.set("normal") # Code for /obj/file1/rop_geometry1/f parm tuple hou_parm_tuple = hou_node.parmTuple("f") hou_parm_tuple.deleteAllKeyframes() hou_parm_tuple = hou_node.parm("f1").set(0) hou_parm_tuple = hou_node.parm("f2").set(int(seq[1])-int(seq[0])) hou_node.setInput(0,delNode) # Code for /obj/file1/rop_geometry1/soppath parm hou_parm = hou_node.parm("sopoutput") hou_parm.set(p.rawValue()+'_CROPPED.bgeo.sc') hou_node.moveToGoodPosition() hou_parm_tuple = delNode.parmTuple("size") hou_parm_tuple.deleteAllKeyframes() hou_parm_tuple = delNode.parmTuple("t") hou_parm_tuple.deleteAllKeyframes()
Principled shader to Octane shaders
for hand wrangling fbx imports. Mileage may vary this is very WIP
#shaders = matNet.children() shaders = hou.selectedItems() for shader in shaders: if shader.type().name() == 'principledshader::2.0': mat = shader #duplicate old material matname = mat.name() materialsPath = mat.parent() duplicate = hou.copyNodesTo([mat],materialsPath)[0] duplicate.setName(matname+'_original') mat.destroy() #need to destroy original one so that materials aren't reassigned #create new one octmat = materialsPath.createNode("octane_vopnet", matname, run_init_scripts=False, load_contents=True, exact_type_name=True) coll = octmat.createNode("octane_material", "octane_material1", run_init_scripts=False, load_contents=True, exact_type_name=True) uni = octmat.createNode("octane::NT_MAT_UNIVERSAL", matname, run_init_scripts=False, load_contents=True, exact_type_name=True) coll.setInput(0,uni) #octmat = materialsPath.createNode("octane_vopnet", matname, run_init_scripts=False, load_contents=True, exact_type_name=True) octmat.moveToGoodPosition() #transfer properties fromMat = duplicate toMat = uni fromParm = ['basecolor','rough'] toParm = ['albedo','roughness'] for i in range(len(fromParm)): toMat.parmTuple(toParm[i]).set(fromMat.parmTuple(fromParm[i]),language=None,follow_parm_references=False) toMat.parmTuple(toParm[i]).deleteAllKeyframes() #is there albedo texture if fromMat.parm('basecolor_useTexture').eval(): texfile = fromMat.parm('basecolor_texture').eval() tex = uni.parent().createNode("octane::NT_TEX_IMAGE", "Texture_Image_RGB", run_init_scripts=False, load_contents=True, exact_type_name=True) tex.parm('A_FILENAME').set(texfile) tex.parm('A_RELOAD').set(1) toMat.setInput(2, tex, 0) toMat.moveToGoodPosition()
jerome 3ds max
https://vimeo.com/moab
Octane
Octane choose IPR dialog (Houdini)
Placed in a shelf button bound to F9 to automatically launch IPRs
import hou def chooseIPRdialog(buttons): try: c = hou.session.choice except: hou.session.choice = 0 buttons.append('Cancel') dialog = hou.ui.displayMessage('IPR choice', buttons=buttons,default_choice=hou.session.choice) hou.session.choice = dialog if dialog == len(buttons)-1: dialog = False return dialog #grab all iprs iprs = [] for node in hou.node('/').allSubChildren(): if node.type().name() == 'Octane_ROP': iprs.append(node) #simple names names = [x.name() for x in iprs] #if we have duplicate names, give a more detailed path if len(names) != len(set(names)): names = [x.path() for x in iprs] #if only one IPR found, launch it otherwise launch dialog, return ipr, launch ipr if not cancelled if len(names) == 1: iprs[0].parm('HO_IPR').pressButton() else: chosenIPR = chooseIPRdialog(names) if chosenIPR is not False: iprs[chosenIPR].parm('HO_IPR').pressButton()
octane change number of GPUs (Houdini)
use this in a prerender/postrender script to change preferences. It's fucking insane that it's not a render option.
Error checking is not the best
import os, sys, hou, datetime, shutil from os.path import exists def disableOneGpu(on = True): threefourthGPUs_octanepref = '//prod3/prod3/RESSOURCES/SANDBOX/bernie/octane.pref' basic_octanepref = '//prod3/prod3/RESSOURCES/SANDBOX/bernie/octane.pref.bak' prefdir = hou.getenv('HOUDINI_USER_PREF_DIR') octanepref = prefdir+'/octane.pref' backup = octanepref + '.bak' if on : print('change houdiniprefs/octane.pref to 3 gpus instead of 4') if exists(backup): time = datetime.datetime.now().strftime("%Y%m%d%H%M%S") os.rename(backup, backup+str(time)) if not exists(octanepref): # in case there is no prefs set shutil.copyfile(basic_octanepref, octanepref) try: os.rename(octanepref, backup) except WindowsError: os.remove(backup) os.rename(octanepref, backup) shutil.copyfile(threefourthGPUs_octanepref, octanepref) else: print('restoring octane.pref') try: os.rename(backup, octanepref) except WindowsError: os.remove(octanepref) os.rename(backup, octanepref) disableOneGpu(1) #grab pref disableOneGpu(0) #restore backup
octane drive (Houdini)
proc string repl(string $s){ $s = substituteAllString($s, "Q:/PROJECT", "//prod3/prod3/PROJECT"); return $s; } if(size(`ls -type "octaneImageTexture"`)>0){ for($tx in `ls -type "octaneImageTexture"`){ $f = getAttr($tx+".File"); $new = repl($f); if($new != $f){ setAttr -type "string" ($tx+".File") $new; warning("Changed texture to "+$new); } } }
Firm studio/faubourg maya sequencer to xml to houdini and auto cam / rops
maya sequencer python export (Python Maya)
re-written version of the xml export thingy which honestly blows
import xml.etree.cElementTree as ET import maya.cmds as mc from xml.dom import minidom #file to write to singleFilter = "*.xml" xmlfile = mc.fileDialog2(fileFilter=singleFilter, dialogStyle=2, fm=0) #sequence info s = mc.ls(type="sequencer")[0] smin = mc.getAttr(s+".minFrame") smax = mc.getAttr(s+".maxFrame") #setup xml root = ET.Element("root") sequence = ET.SubElement(root, "sequence") ET.SubElement(sequence, "start").text = str(smin) ET.SubElement(sequence, "end").text = str(smax) media = ET.SubElement(sequence, "media") video = ET.SubElement(media, "video") for cs in mc.listConnections(s+".shots"): cam = mc.connectionInfo( cs+".currentCamera", sourceFromDestination=True).split('.message')[0] implane = "" try: implane = mc.listConnections(cs+".clip",s=True)[0].split('->')[1] implane = mc.getAttr(implane+".imageName") except: implane = "" shotin = str(mc.getAttr(cs+".startFrame")) shotout = str(mc.getAttr(cs+".endFrame")) sequenceStart = str(mc.getAttr(cs+".sequenceStartFrame")) sequenceEnd = str(mc.getAttr(cs+".sequenceEndFrame")) track = ET.SubElement(video, "track") clipitem = ET.SubElement(track, "clipitem", id=cs) ET.SubElement(clipitem, "start").text = shotin ET.SubElement(clipitem, "end").text = shotout ET.SubElement(clipitem, "sequenceStart").text = sequenceStart ET.SubElement(clipitem, "sequenceEnd").text = sequenceEnd ET.SubElement(clipitem, "name").text = cam camPath = mc.ls(cam,l=1)[0] camPath = "/".join(camPath.split('|')[-2:]) ET.SubElement(clipitem, "camera").text = camPath file = ET.SubElement(clipitem, "file") ET.SubElement(file, "pathurl").text = "file://"+implane tree = ET.ElementTree(root) #hackish but necessary to pretty print xml xmlstr = minidom.parseString(ET.tostring(root)).toprettyxml(indent=" ") with open(xmlfile[0], "w") as f: f.write(xmlstr)
houdini xml to cameras (using custom hda)
import tkinter as tk from lxml import etree from tkinter import filedialog import re import hou root = tk.Tk() root.withdraw() reg = r'^(.+?)([0-9]+)\.(png|exr|jpg)$' file_path = filedialog.askopenfilename() print(file_path) tree = etree.parse(file_path) #set sequence playback range from xml hou.setFps(25) sequence = tree.xpath("/root/sequence")[0] seqStart = int(float(sequence.find("start").text)) seqEnd = int(float(sequence.find("end").text)) hou.playbar.setFrameRange(seqStart,seqEnd) hou.playbar.setPlaybackRange(seqStart,seqEnd) print('setting sequence start/end: {}-{}'.format(seqStart,seqEnd)) elmts = [] for shot in tree.xpath("/root/sequence/media/video/track/clipitem"): id = shot.attrib['id'] start = shot.find("start").text end = shot.find("end").text startS = shot.find("sequenceStart").text endS = shot.find("sequenceEnd").text camera = shot.find("camera").text imseq = shot.find("file/pathurl").text match = re.match(reg, imseq,re.IGNORECASE) if match: imseq = match.groups()[0].split('file://')[1]+'$F'+str(len(match.groups()[1]))+'.'+match.groups()[2] elmts.append([id,startS,endS,imseq,camera,start,end]) #sort by start frame elmts = sorted(elmts, key = lambda x: x[1]) try: hou.hda.installFile('path/to/cameras.hda', oplibraries_file=None, change_oplibraries_file=True, force_use_assets=False) except: print('\n\n/!\ Bug\n\n') items = [] #setup camera switcher from chop camRender = hou.node('/obj').createNode("cam", "camRender", run_init_scripts=True, load_contents=True, exact_type_name=True) chop = hou.node('/obj').createNode("chopnet", "camSwitcher", run_init_scripts=False, load_contents=True, exact_type_name=True) switch = chop.createNode("switch", "switch", run_init_scripts=False, load_contents=True, exact_type_name=True) sopswitch = hou.node('/obj').createNode('switcher','renderCam') #just for preview purpose #set preview camera kf = hou.StringKeyframe() kf.setTime(0) kf.setExpression("inputs = hou.node('/obj/renderCam').inputs()\ns = hou.parm('/obj/renderCam/camswitch').eval()\nreturn hou.parm(inputs[s].path()+'/renderCam/vm_background').eval()\n", hou.exprLanguage.Python) camRender.parm('vm_background').setKeyframe(kf) xport = chop.createNode("export", "toCam", run_init_scripts=False, load_contents=True, exact_type_name=True) xport.setExportFlag(True) xport.setDisplayFlag(True) xport.setUnloadFlag(False) prm = xport.parm("channels") prm.set("*") prm = xport.parm("nodepath") prm.set("../../camRender") prm = xport.parm("path") prm.set("t[xyz] r[xyz] focal aperture") xport.setInput(0,switch) items.append(chop) items.append(sopswitch) items.append(camRender) i = 0 for el in elmts: start = int(float(el[1])) end = int(float(el[2])) startS = int(float(el[5])) print('[{}-{}] \t\tCam {}'.format(start,end,el[0])) #cam hda parms cam = hou.node('/obj').createNode('camera',el[0]) cam.setDisplayFlag(0) camPath = cam.path()+'/CAMERAS/'+el[4] cam.parm('camera').set(camPath) cam.parm('startendx').set(start) cam.parm('startendy').set(end) cam.parm('frame_offset').set(start-startS) cam.parm('bg').set(1) cam.parm('imseq').set(el[3]) cam.parm('bg_offset').set(-start) sopswitch.setNextInput(cam) fetch = chop.createNode("fetchchop", "fetch"+el[0], run_init_scripts=False, load_contents=True, exact_type_name=True) fetch.parm("nodepath").set(cam.path()+"/chopnet1/shift1") switch.setNextInput(fetch); #keyframes kf = hou.Keyframe() kf.setFrame(start) kf.setValue(i) kf.setSlope(0) kf.setInSlope(0) kf.useSlope(False) kf.setAccel(0) kf.useAccel(False) kf.interpretAccelAsRatio(False) kf.setExpression("constant()", hou.exprLanguage.Hscript) switch.parm('index').setKeyframe(kf) sopswitch.parm('camswitch').setKeyframe(kf) items.append(cam) i = i + 1 hou.node('/obj').layoutChildren(items=items)
Bake selected cams (Houdini)
import hou for camShot in hou.selectedNodes(): p = camShot.position() cam = hou.node('/obj').createNode("cam", str(camShot)+'Render', run_init_scripts=True, load_contents=True, exact_type_name=True) cam.setPosition(p) cam.move(hou.Vector2(0, -2)) hou_node = hou.node('/out').createNode("bake_animation", "bake_animation1", run_init_scripts=False, load_contents=True, exact_type_name=True) hou_parm = hou_node.parm("range") hou_parm.deleteAllKeyframes() hou_parm.set("user") hou_parm_tuple = hou_node.parmTuple("start_end") hou_parm_tuple.deleteAllKeyframes() s = camShot.parm('startendx').eval() e = camShot.parm('startendy').eval() hou_parm_tuple.set((s-1, e+1)) hou_parm = hou_node.parm("parm_filter") hou_parm.deleteAllKeyframes() hou_parm.set("t[xyz] r[xyz] aperture focal") hou_parm = hou_node.parm("source") hou_parm.deleteAllKeyframes() hou_parm.set(camShot.path()+"/renderCam") hou_parm = hou_node.parm("target") hou_parm.deleteAllKeyframes() hou_parm.set(cam.path()) hou_parm = hou_node.parm("copy_parameters") hou_parm.deleteAllKeyframes() hou_parm.set(1) hou_parm = hou_node.parm("copy_transforms") hou_parm.deleteAllKeyframes() hou_parm.set(1) hou_parm = hou_node.parm("write_to_chop_channel") hou_parm.deleteAllKeyframes() hou_parm.set(1) hou_node.parm('execute').pressButton() hou_node.destroy(1) switcher = camShot.outputs()[0] inputs = switcher.inputs() index = inputs.index(camShot) switcher.setInput(index, cam, output_index=0)
Reference copy /out/rops and octane rendertargets
import hou def delp(parmpath): '''delete parm''' hou_parm = hou.parm(parmpath) hou_parm.lock(False) hou_parm.deleteAllKeyframes() unrefParms = ['f1','f2','HO_renderCamera','HO_iprCamera','HO_renderTarget','HO_img_fileName'] #grab the octane main setting rop in /out rop = hou.selectedNodes()[0] #grab the /geo cam switcher and figure out the frame ranges + cameras switcher = hou.node('/obj/renderCam') inputs = switcher.inputs() keyframes = switcher.parm('camswitch').keyframes() startFrames = [int(i.frame()) for i in keyframes] endFrames = [i-1 for i in startFrames[1:]] endFrames.append(int(hou.playbar.frameRange()[1])) cams = [inputs[int(i.value())] for i in keyframes] beautyName = ['_'.join(n.path().split('/')[-1].split('_')[:2]) for n in cams] numCams = len(cams) ropList = [] #iterate through the cameras and create a ROP associated with each cam for i in range(numCams): print('{}-{} \t{} ({})'.format(startFrames[i],endFrames[i],beautyName[i],cams[i])) copy = hou.node('/out').copyItems([rop],1)[0] copy.setPosition(rop.position()) copy.move(hou.Vector2(2.3*(i+1), 0)) copy.setName(beautyName[i]) rt = hou.node(rop.parm('HO_renderTarget').eval()) rtcopy = rt.parent().copyItems([rt],1)[0] rtcopy.setPosition(rt.position()) rtcopy.move(hou.Vector2(2.3*(i+1), 0)) #print(beautyName[i]+'_renderTarget') rtcopy.setName(beautyName[i]+'_renderTarget') for parm in ['parmEnvironment','A_FILENAME']: delp(rtcopy.path()+'/'+parm) for parm in unrefParms: delp(copy.path()+'/'+parm) copy.parm('f1').set(startFrames[i]) copy.parm('f2').set(endFrames[i]) copy.parm('HO_renderCamera').set(cams[i].path()) copy.parm('HO_iprCamera').set(cams[i].path()) copy.parm('HO_renderTarget').set(rtcopy.path()) copy.parm('HO_img_fileName').set(rop.parm('HO_img_fileName').rawValue())
import hou rc = hou.node('/obj/renderCam') curcam = rc.inputs()[rc.parm('camswitch').eval()] count = 0 for node in hou.node('/out').children(): count = count + 1 if node.type().name() == 'Octane_ROP': if str(curcam) in str(node.parm('HO_renderCamera').eval()): node.parm('HO_IPR').pressButton() break;
ellipse redshift debug
import maya.cmds as cmds ro = cmds.ls("redshiftOptions") attrs = cmds.listAttr(ro) print("\n\n\n###############################################\nimport maya.cmds as cmds\n\n") for o in attrs: try: get = cmds.getAttr(ro[0]+"."+str(o)) #print type(get) if get != '': if str(type(get)) == "<type 'unicode'>": get = "'"+get+"', type='string'" if str(type(get)) == "<type 'list'>": get = ','.join(map(str,get[0])) get = get + ", type='double3'" #get = join(str(i) for i in get[0]) if str(get) == "None": print("# cmds.setAttr('"+ro[0]+"."+str(o)+"'," + str(get)+')') else: print("cmds.setAttr('"+ro[0]+"."+str(o)+"'," + str(get)+')') else: print("# cmds.setAttr('"+ro[0]+"."+str(o)+"'," + str(get)+')') except: print("# "+o+" fail")
aveillan truc cheveu
string $sel[] = `ls -sl`; for($obj in $sel){ //$obj = $sel[0]; string $children[] = `listRelatives -f $obj`; string $children[] = `listRelatives -f $children[2]`; $obj2 = $children[0]; addAttr -ln "dist" -at double $obj2; setAttr -e -keyable true {$obj2+".dist"}; string $exp = ($obj2+".dist = "+$obj+".translateZ - ani_loc.translateZ;"); expression -s $exp -o $obj2; setDrivenKeyframe -v 200 -dv 0 -currentDriver ($obj2+".dist") ($obj2+".rotateX"); setDrivenKeyframe -v 0 -dv 1 -currentDriver ($obj2+".dist") ($obj2+".rotateX"); }
Fixstudio excel plot to remap color values
import re b = """0.0202020202 0.0012355819 0.0303030303 0.0018490148 0.0404040404 0.0024572181 0.0505050505 0.0030584484 0.0606060606 0.0036509625 0.0707070707 0.0042330173 0.0808080808 0.0048028694 0.0909090909 0.0053587757""" strg = "float $v[] = {" lines = re.split(r'\n+', b) for word in lines: for v in re.split(r'\t',word): strg = strg+str(float(v))+"," strg = strg + "1,1};" print strg
copy paste str
float $v[] = {0.0202020202,0.0012355819,0.0303030303,0.0018490148,0.0404040404,0.0024572181,0.0505050505,0.0030584484,0.0606060606,0.0036509625,0.0707070707,0.0042330173,0.0808080808,0.0048028694,0.0909090909,0.0053587757,1,1}; for($i=0;$i<size($v);$i+=2){ int $cur = $i+2; setAttr remapColor6.red[$cur].red_FloatValue ($v[$i+1]); setAttr remapColor6.red[$cur].red_Position ($v[$i]); setAttr remapColor6.red[$cur].red_Interp 1; }
Fixstudio IES visualizer
//place in a scriptjob on frame change scene open; maxwell deosn't work with prerender mels int $ti = `currentTime -q`; string $filepath = "/prod/prod1/Projets/RESSOURCES/_LIB/3D/maya/scenes/LIGHTING/_ies/!preview/IESlist.txt"; string $readAllLines[] = `freadAllLines($filepath)`; string $curfile = $readAllLines[$ti]; $filepart = `match "[^/\\]*$" $curfile`; setAttr -type "string" maxwellRenderOptions.mxOverlayText $filepart; setAttr -type "string" "maxwellEmitter21.iesFile" $curfile; //should be the emitter BSDF
Vray to Maxwell VDB placeholder
string $objs[] = `ls -sl`; for($o in $objs){ //$o = $objs[0]; string $f = `getAttr($o+".inFile")`; string $range = `getAttr($o+".inCacheRange")`; $rangeArray = stringToStringArray($range, " - "); $maxVol = `createNode maxwellVolumetricObject`; setAttr ($maxVol+".useConstantDensity") 3; string $transforms[] = `listRelatives -p`; $tr = $transforms[0]; //check if it's an animated VDB with vray's framerange, if it is, replace #### with 0000 if(size($rangeArray)>0){ if(getAttr($o+".inPlayAt")==1){ setAttr ($o+".inPlayAt") 0; setAttr ($o+".inReadOffset") 0; } setAttr -type "string" ($maxVol+".file ") (substituteAllString($f, "####", "0000")); setAttr ($maxVol+".useCurrentFrame") 0; string $expr = "if("+$o+".inMode==0){\n"+$maxVol+".time = frame-"+$o+".inPlayAt;\n}else{\n"+$maxVol+".time = "+$o+".inIndex;\n};"; $expr += "\n"+$tr+".visibility=("+$maxVol+".time>="+$rangeArray[0]+"&&"+$maxVol+".time<="+$rangeArray[1]+")?1:0;"; expression -s $expr; }else{ setAttr -type "string" ($maxVol+".file ") ($f); } parent $tr $o; makeIdentity $tr; }
Random replace instance
global float $deletepercentage; if(`objExists("instances_set")`){delete "instances_set";}; if(`objExists("replacingobjs_set")`){delete "replacingobjs_set";}; string $window = `window -menuBar true -title "Random replace"`; columnLayout -adjustableColumn true; $a = `button -label "Instance Objects"`; button -e -command ("setSet(\"instances_set\",\""+$a+"\",\"Instance Objects\")") $a; $b = `button -label "Objects To Replace"`; button -e -command ("setSet(\"replacingobjs_set\",\""+$b+"\",\"Objects To Replace\")") $b; $c = `button -label ("Random delete ("+$deletepercentage+"%)")`; button -e -command ("setDelete(\""+$c+"\")") $c; button -label "Go!" -command ("replaceWithInstances;deleteUI -window \""+$window+"\";"); showWindow $window; proc setSet(string $name,string $button,string $buttonString){ string $selectedElmts[] = `ls -sl -tr`; if(`objExists $name`){ delete $name; } sets -n $name $selectedElmts; button -e -label ($buttonString+" ("+size($selectedElmts)+")") $button; select -cl; } proc setDelete(string $btn){ global float $deletepercentage; string $text; string $result = `promptDialog -title "Delete random %" -message "Set chance of being deleted (0-100):" -button "OK" -button "Cancel" -defaultButton "OK" -cancelButton "Cancel" -dismissString "Cancel"`; if ($result == "OK") { $text = `promptDialog -query -text`; $deletepercentage = float($text); button -e -label ("Random delete("+$deletepercentage+"%)") $btn; } } global proc replaceWithInstances(){ global float $deletepercentage; string $instances[] = `listConnections -s 1 -d 0 -p 0 -c 0 "instances_set"`; string $objs[] = `listConnections -s 1 -d 0 -p 0 -c 0 "replacingobjs_set"`; int $end = size($objs)-1; global string $gMainProgressBar; // This is defined on maya startup progressBar -edit -beginProgress -isInterruptable true -status "Replacing with instances" -maxValue $end $gMainProgressBar; refresh -su 1; for($i = 0;$i<=$end;$i++){ if(`progressBar -query -isCancelled $gMainProgressBar`) break; if(`rand 1` > ($deletepercentage/100)){ select -r $objs[$i] $instances[int(floor(rand(size($instances))))] ; replaceObjects 1 1 1 1; }else{ delete $objs[$i]; } progressBar -edit -step 1 $gMainProgressBar; } progressBar -edit -endProgress $gMainProgressBar; refresh -su 0; }
Import vray proxies with vrmesh names
Override vray import procs to allow use of filenames as mesh names instead of the silly 'mesh' default name
proc string prepareStringArg(string $s) { string $subs = substitute("\"", $s, "\\\""); return "\"" + $subs + "\""; } proc string preparePathArg(string $s) { return prepareStringArg(fromNativePath($s)); } proc vrayCreateProxyExisting(string $node, string $fileNameArray[], string $objectPath,int $useFileName) { global int $g_vrayImportProxy_animStart; global int $g_vrayImportProxy_animLength; global int $g_vrayImportProxy_hasFrameFilter; for($fileName in $fileNameArray) { string $anim = ""; if ($g_vrayImportProxy_hasFrameFilter) { $anim = (" -animStart " + $g_vrayImportProxy_animStart + " -animLength " + $g_vrayImportProxy_animLength); } //added by bernie if($useFileName){ string $filepart = `match "[^/\\]*$" $fileName`; $node = `match "^[^\.]*" $filepart`; //i'm bad at regex } string $cmd = ("vrayCreateProxy" + " -node " + prepareStringArg($node) + " -dir " + preparePathArg($fileName) + " -existing " + " -createProxyNode " + $anim + " -objectPath " + prepareStringArg($objectPath)); eval $cmd; } } global proc vrayCreateProxyButtonProc(string $nodeNameCtrl, string $fileNameArray[], string $objectPathCtrl, string $singleModeCtrl, string $animLabelCtrl, string $browseModeUseFilename) { int $useFileName = `checkBox -q -value $browseModeUseFilename`; string $node = `textField -q -text $nodeNameCtrl`; string $objectPath = `textField -q -text $objectPathCtrl`; int $singleFileMode = `radioButton -q -select $singleModeCtrl`; // Before importing a proxy first trigger the execution of vrayProxyFilesAreReadable for single proxy mode only in order to re-evaluate // the animation boundaries when frame formatting is inserted in the filename field without an action leading to the execution of its change command if ($singleFileMode) vrayProxyFilesAreReadable($fileNameArray, $animLabelCtrl); vrayCreateProxyExisting($node, $fileNameArray, $objectPath,$useFileName); } global proc vrayCreateImportProxyWindow() { string $window = `window -rtf true -title "Import V-Ray proxy"`; formLayout -nd 100 cpwLyt; string $nodeNameLabel = `text -label "Node name: "`; string $fileNameLabel = `text -label "File(s):"`; string $objectPathLabel = `text -label "Object path:"`; string $animLabel = `text -l ""`; string $nodeNameCtrl = `textField -text "mesh" -w 190`; string $fileNameCtrl = `textField -w 190`; textField -e -annotation "Frame formatting is supported via <frameNN> to specify a sequence of proxy files." $fileNameCtrl; string $fileListCtrl = `scrollField -w 190 -h 120 -visible false -editable false`; string $objectPathCtrl = `textField -text "" -w 190`; string $cmdBrowse = ""; string $browseModeRadioGrp = `radioCollection`; string $browseModeSingle = `radioButton -label "Single file (frame formatting is supported)" -select`; string $browseModeMultiple = `radioButton -label "Multiple files"`; //added by bernie string $browseModeUseFilename = `checkBox -label "Use filename as mesh name" -value false`; global float $g_mayaVersion; string $cmdGetProxyFiles = "vrayGetProxyFiles(\"" + $fileNameCtrl + "\",\"" + $fileListCtrl + "\", eval(\"radioButton -q -select " + $browseModeSingle + "\"))"; string $cmdCreateProxy = "vrayCreateProxyButtonProc(\"" + $nodeNameCtrl + "\","+$cmdGetProxyFiles+",\""+$objectPathCtrl + "\",\""+$browseModeSingle+"\",\""+$animLabel+"\",\""+$browseModeUseFilename+"\");"; $cmdCreateProxy += "deleteUI -window " + $window; string $createButton = `button -enable false -label "Create" -align "center" -c $cmdCreateProxy`; string $cmdFileNameChanged = "vrayImportProxyUpdateCreateBtn(\""+$createButton+"\", "+$cmdGetProxyFiles+", \""+$animLabel+"\")"; textField -e -cc $cmdFileNameChanged -ec $cmdFileNameChanged -rfc $cmdFileNameChanged $fileNameCtrl; scrollField -e -cc $cmdFileNameChanged -ec $cmdFileNameChanged $fileListCtrl; if ($g_mayaVersion >= 2011) $cmdBrowse = ("vrayImportProxyBrowseCmd(\"" + $fileNameCtrl + "\",\"" + $fileListCtrl + "\",true, \""+$createButton+"\", \""+$animLabel+"\")"); else $cmdBrowse = "{textField -e -text `fileDialog -dm \"*.vrmesh *.abc\"` "+$fileNameCtrl+"; setFocus "+$fileNameCtrl+";}"; string $browseButton = `symbolButton -image "navButtonBrowse.xpm" -c $cmdBrowse browser`; setFocus $nodeNameCtrl; string $cmdFileMode = "vrayProxySetFileMode(\"" + $window + "\",\"" + $fileNameCtrl + "\",\"" + $fileListCtrl + "\",\""; $cmdFileMode = $cmdFileMode + $animLabel + "\",\"browser\",\""+ $browseModeSingle + "\",\"" + $createButton; $cmdFileMode = $cmdFileMode + "\",\"" + $objectPathLabel + "\",\"" + $objectPathCtrl + "\");"; radioButton -e -onCommand ($cmdFileMode) $browseModeSingle; radioButton -e -onCommand ($cmdFileMode) $browseModeMultiple; //added by bernie checkBox -e -onCommand ("textField -e -en 0 "+$nodeNameCtrl) $browseModeUseFilename; checkBox -e -offCommand ("textField -e -en 1 "+$nodeNameCtrl) $browseModeUseFilename; formLayout -e -af $browseModeSingle top 5 -af $browseModeSingle left 5 -ac $browseModeMultiple top 5 $browseModeSingle -af $browseModeMultiple left 5 -ac $browseModeUseFilename top 5 $browseModeMultiple -af $browseModeUseFilename left 5 -ac $nodeNameLabel top 10 $browseModeUseFilename -af $nodeNameLabel left 5 -ac $fileNameLabel top 5 $nodeNameCtrl -af $fileNameLabel left 5 -ac $nodeNameCtrl top 10 $browseModeUseFilename -ac $nodeNameCtrl left 5 $nodeNameLabel -af $nodeNameCtrl right 35 -ac $fileNameCtrl top 5 $nodeNameCtrl -ac $fileNameCtrl left 5 $nodeNameLabel -af $fileNameCtrl right 35 -ac $fileListCtrl top 0 $fileNameCtrl -ac $fileListCtrl left 5 $nodeNameLabel -af $fileListCtrl right 35 -af $fileListCtrl bottom 80 -ac $objectPathLabel top 5 $fileNameCtrl -af $objectPathLabel left 5 -ac $objectPathCtrl top 5 $fileNameCtrl -ac $objectPathCtrl left 5 $nodeNameLabel -af $objectPathCtrl right 35 -ac $animLabel top 5 $objectPathCtrl -aoc $animLabel left 0 $fileNameCtrl -ac $browseButton top 5 $nodeNameCtrl -ac $browseButton left 5 $nodeNameCtrl -ac $createButton top 25 $objectPathCtrl -af $createButton left 70 -af $createButton right 35 cpwLyt; // If we set it during creation, the size will be ignored, since Maya saves size/pos. for each window. global int $importProxyWndDefaultHeight; window -e -wh 305 $importProxyWndDefaultHeight -sizeable true $window; showWindow $window; } vrayCreateImportProxyWindow;
Small: bake turtle maps with animation
haven't found a simpler way than call a batch multiple times
#maya-render-new is aliased to maya/bin/render for i in {1..100} do maya-render-new -preRender \"currentTime -e $i\" glass_normals_maker.mb done
Small: vray ies library
import os import os.path import maya.cmds as mc import ntpath #get all IES and write to file iesPath = '/u/mglib/IMAGES/VRAY_IES/' target = open(iesPath+'IESlist.txt', 'w') ieslist = [] for dirpath, dirnames, filenames in os.walk(iesPath): for filename in [f for f in filenames if f.endswith('.ies')]: ieslist.append(os.path.join(dirpath, filename)) target.write('All IES ---- auto generated\n') target.write('\n'.join(ieslist)) target.close() #create a vray light per item, set visibility keyframes, rename count = 1 for ies in ieslist: light = mc.createNode('VRayLightIESShape') lightTransform = mc.listRelatives(light,parent=1) mc.setAttr(light+'.iesFile',ies,type='string') lightTransform = mc.rename(lightTransform,'ies_'+os.path.splitext(ntpath.basename(ies))[0]) mc.setKeyframe( lightTransform, attribute='visibility', t=[-1.0+count,1.0+count],v=0.0 ) mc.setKeyframe( lightTransform, attribute='visibility', t=[0.0+count],v=1.0 ) count += 1 #render....
select all children but last ones (tails)
import maya.cmds as mc selectAllbutEnd = [] l = mc.ls(sl=1) for o in l: selectAllbutEnd.extend(mc.listRelatives(o,c=1,ad=1)[1:]) selectAllbutEnd.append(o) mc.select(selectAllbutEnd)
méca g grimbergen setup
stepped, requires loads of defs
############################################################### JNTS CREATION ########################################## #single edge edgeSelection = mc.ls(sl=1) #mc.select(edgeSelection,r=1) #for each selection, get edge loop and add it to list edgeLoops = [] for edge in edgeSelection: mc.select(edge, r=1) mel.eval('SelectEdgeLoopSp') edgeLoop = mc.ls(sl=1, fl=1) edgeLoops.append(edgeLoop) #create joint chain on each edge loop joints = [] for loop in edgeLoops: joints.append(bonesFromEdgeLoop(loop, 3, [0,0,4])) boundJoints = [] flatList = [] for jntChain in joints: currentChain = [] for i in range(len(jntChain)-1): currentChain.append(jntChain[i]) flatList.append(jntChain[i]) boundJoints.append(currentChain) mc.select(flatList) #joints to skin with (boundjoints is a comprehensive list) ################ do skinning, with neighbours AND selected joints only ######### ############################################################### AUTOMATIC WEIGHTS ########################################## o = mc.ls(edgeLoops[0][0],o=1) sc = mel.eval('findRelatedSkinCluster("'+str(o[0])+'")') for i in range(len(edgeLoops)): #print i counter = i edgeLooptoFaces = mc.polyListComponentConversion(edgeLoops[counter],tf=True ) face1 = mc.ls(edgeLooptoFaces,fl=1)[0] face1 = int(face1.split('[')[-1].split(']')[0]) shell = mc.polySelect(o,ets=face1) shellVtx = mc.polyListComponentConversion(tv=1) antiList = flatList for jnt in boundJoints[counter]: antiList = [x for x in antiList if x != jnt] removeInfluences = [] for jnt in antiList: removeInfluences.append((str(jnt),0)) mc.skinPercent(sc,str(shellVtx[0]),tv=removeInfluences) ############################################################### AIM CONSTRAINTS ########################################### attachCurve = u'curve1' attachTopGeo = u'targetPlane' sel = mc.ls(sl=1) parents = [] for o in sel: d = mc.duplicate(o, po=1) d = mc.rename(d,str(o)+"_aimJnt") mc.parent(o,d) parents.append(d) targetJoints = [] for o in parents: relatives = mc.listRelatives(o,c=1,ad=1) endJoint = relatives[0] targetJoint = mc.duplicate(endJoint)[0] mc.parent(targetJoint,endJoint) mc.setAttr(targetJoint+".tx",1) mc.setAttr(targetJoint+".displayHandle",1) targetJoints.append(targetJoint) ###### place target joints properly ######### fails = [] follicles = [] for o in parents: topPos = intersect(o,attachTopGeo) if topPos == 0 : fails.append(o) else : follicle = closestUV(topPos,attachTopGeo,1) relatives = mc.listRelatives(o,c=1,ad=1) endJoint = relatives[0] endJointPos = mc.xform(endJoint,ws=1,t=1,q=1) loc = mc.spaceLocator()[0] mc.setAttr ( '%s.translate' % loc, endJointPos[0], endJointPos[1], endJointPos[2] ) mc.select(loc,attachCurve,r=1) attachToClosestPointOnCurve(0) mc.aimConstraint(loc,o,wuo=str(follicle),wut="object",mo=1) mc.rename(loc,o+"_aimLoc") mc.delete(endJoint) mc.select(fails) # if there's a selection, fix stuff
#fix stuff # jntsEnd = mc.ls(sl=1) placement = [] for end in jntsEnd: t = mc.getAttr(end+".translate") placement.append([end,t]) #copy right to left for i in range(len(placement)): ag = placement[i][0].replace('aile_d','aile_g') x = placement[i][1][0][0] y = placement[i][1][0][1] z = -placement[i][1][0][2] mc.setAttr(ag+".tx",x) mc.setAttr(ag+".ty",y) mc.setAttr(ag+".tz",z)
add hdri ctrl
string $hdriCtrl = `createNode transform -n "hdriCtrl"`; createNode nurbsCurve -n "hdriCtrlShape" -p "hdriCtrl"; setAttr -k off ".v"; setAttr ".cc" -type "nurbsCurve" 3 18 0 no 3 23 0 0 0 1 2 3 4 5 6 7 8 8 8 9 10 11 12 13 14 15 16 16 16 21 3.1773138824361804 -0.098334400976111055 -0.0019187323799920489 3.113926460204997 -1.0102159734494798 -0.0019187323799917117 2.3575241134550451 -2.527169584847317 -0.0019187323799910387 -0.010427481731231687 -3.3385769758437815 -0.0019187323799906781 -2.2844758477551599 -2.2848481947115693 -0.0019187323799911471 -3.1842745118033569 0.055871506457036514 -0.0019187323799921855 -2.2040990750523348 2.3640878023122807 -0.001918732379993211 0.10501572631038342 3.3385769758437815 -0.0019187323799936434 2.443503170980458 2.4457986257314182 -0.0019187323799932476 3.1470150388890095 0.90360414350370477 -0.0019187323799925633 3.1842745118033569 0.009587422878553388 -0.0019187323799922265 3.1470150388890095 -0.0019187323799924878 0.90360414350370555 2.443503170980458 -0.0019187323799924878 2.4457986257314182 0.10501572631038342 -0.0019187323799924878 3.3385769758437815 -2.2040990750523348 -0.0019187323799924878 2.3640878023122815 -3.1842745118033569 -0.0019187323799924878 0.055871506457036847 -2.2844758477551599 -0.0019187323799924878 -2.2848481947115684 -0.010427481731231687 -0.0019187323799924878 -3.3385769758437815 2.3575241134550451 -0.0019187323799924878 -2.527169584847317 3.113926460204997 -0.0019187323799924878 -1.0102159734494789 3.1773138824361804 -0.0019187323799924061 -0.093784440343312514; string $expr = "maxwellRenderOptions.environment[0].envOffsetU="+$hdriCtrl+".rotateY%360;maxwellRenderOptions.environment[0].envOffsetV="+$hdriCtrl+".rotateX%360;"; expression -s $expr; setAttr -lock true ($hdriCtrl+".rz"); select -r $hdriCtrl; setToolTo RotateSuperContext;
evermotion cleaning
//to do: group according to mesh name (arch75_065_001+arch75_065_002 etc) //set group name string $objs[] = `ls -sl`; for($o in $objs){ string $buffer[] = {}; string $r[] = `listRelatives $o`; $numTokens = `tokenize $r[0] "_" $buffer`; rename $o ($buffer[0]+"_"+$buffer[1]); } //rename shaders string $objs[] = `ls -sl`; for($o in $objs){ string $sh[] = `listRelatives -s $o`; string $lc[] = `listConnections $sh[0]`; if(`nodeType $lc[0]` == "shadingEngine"){ string $buffer[] = {}; string $shd[] = `listConnections ($lc[0]+".surfaceShader")`; //$numTokens = `tokenize $sh[0] "_" $buffer`; rename $lc[0] ($o+"_matSG"); rename $shd[0] ($o+"_mat"); } } //reload file textures for($t in `lsType "file"`){ AEfileTextureReloadCmd ($t+".fileTextureName"); } //reassign fileTextures so there are no duplicates string $fileTextures[] = `lsType "file"`; string $files[] = {}; string $shader[] = {}; for($t in $fileTextures){ if($t != "<done>"){ $files[size($files)] = `getAttr($t+".fileTextureName")`; string $con[] = `listConnections -s 0 -d 1 -p 1 $t`; $shader[size($shader)] = $con[0]; } } for($i=0;$i<size($files);$i++){ for($j = $i+1;$j<size($files);$j++){ if($files[$j] == $files[$i] && $files[$j] != "changed"){ $files[$j] = "changed"; print("connectAttr -f (\""+$fileTextures[$i]+".outColor\") (\""+$shader[$j]+"\");\n"); //connectAttr -force ($fileTextures[$i]+".outColor") ($shader[$j]); } } }
python
############################################################## # Author: Zachary Cole # Website: http://www.nzaneproductions.com ############################################################## # # Copyright: Creative Commons # Attribution-ShareAlike 3.0 Unported License # # This work is licensed under the # Creative Commons Attribution-ShareAlike 3.0 Unported License. # To view a copy of this license, # visit http://creativecommons.org/licenses/by-sa/3.0/ # or send a letter to # Creative Commons # 444 Castro Street, Suite 900, # Mountain View, California, 94041, USA. # # what does the above copyright mean? # give me credit, and share any modifications you make! thanks! # ############################################################## # # what does this code snippet do? # # it relinks materials imported from a .vrscene to # geometry imported from a .fbx file when you wish # to use a scene created for vray for 3dsmax in # a scene in vray for maya # ############################################################## # caveats? please save backup copies of your work. # I'm not responsible if it finds the # higgs boson or anything unexpected. # the steps below assume you know how to do basic # actions in both 3ds max and maya # support? are you paying for this? no. # if you want to pay for it, # then I'll try and support it. # testing? minimal testing in 3dsmax 2012 w/ vray 2 # and maya 2011 w/ vray 1.5 # feedback? post comments on my blog!! :-) # # assumptions? I'm assuming that the named order is the # same in both formats. # i.e. the first brdf corresponds # to the first phong. (seems to work) ############################################################## # IMPORTANT steps: # in 3ds max: # select all the geometry you want to transfer # save selected as new scene # open scene you just saved # export fbx # export .vrscene # in maya: # change renderer to vray # import fbx # import .vrscene # fix texture paths in hypershade # run this script in the python window of the script editor # # wow i think these header comments are longer than my code. geeze. ############################################################## import maya.cmds as cmds def relinkVrayMaterials(): # get em while they're hot mats = cmds.ls(materials=True) phongs = [] materials = [] submaterials = [] print "#### searching through materials..." # cycle through all materials for mat in mats: # look for shaders that match the naming # when you bring them in from .fbx if cmds.nodeType(mat) == "phong": phongs.append(mat) # look for shaders that match the naming # when you bring them in from .vrscene elif mat.find("brdf") == 0 or mat.find("material") == 0: if mat not in submaterials: materials.append(mat) # layered shaders are special cases # the connected shaders will not match up to the # phong shaders from the fbx if cmds.nodeType(mat) == "layeredShader": # get the connected attrs arr = cmds.listAttr(mat + ".inputs", m=True) for a in arr: # we only care about the color inputs if a[-6:] == ".color": # get the connected nodes conn = cmds.listConnections(mat + "." + a) # add them to the ignored submaterials list for c in conn: submaterials.append(c) print "#### replacing material assigments..." # cycle through all phong materials for i in range(0, len(phongs)): pho = phongs[i] mat = materials[i] # these vray materials don't have shader groups when # they are imported from .vrscenes, so let's make one for each matSG = cmds.sets( renderable=True, noSurfaceShader=True, empty=True, name=mat+'SG' ); cmds.connectAttr( mat+".outColor", mat+"SG.surfaceShader", force=True) # get the objects assigned to the phong objs = cmds.hyperShade(objects=pho) # assign new material to selected objects cmds.hyperShade(assign=mat) print "#### assigned %s to %s assigned objects" % (mat, pho) print "#### done" relinkVrayMaterials()
clean fucked up vertices
string $objs[] = `ls -sl`; for($o in $objs){ string $pp[] = `polyPlane -w 1 -h 1 -sx 1 -sy 1 -ax 0 1 0 -cuv 2 -ch 0`; string $pu[] = `polyUnite -ch 0 -mergeUVSets 1 $pp[0] $o`; select -r ($pu[0]+".f[0]"); doDelete; rename $pu[0] $o; }
rapid rig mirror controllers
//if it's buggy, it's because bernie global string $cb; window -t "mirror controllers rrig"; columnLayout; separator -style "none" -h 5; rowLayout -nc 2; separator -style "none" -w 10; $cb = `checkBox -label "use mirror ( check if buggy )"`; setParent..; separator -style "none" -h 5; rowLayout -nc 5; separator -style "none" -w 10; button -label " Left >> Right " -command "rapidRigMirrorControllers 0"; separator -style "none" -w 10; button -label " Left << Right " -command "rapidRigMirrorControllers 1"; separator -style "none" -w 10; setParent..; separator -style "none" -h 10; showWindow; proc rapidRigMirrorControllers(int $side){ global string $cb; string $objs[] = `ls -sl -l`; //if it's a vertex/cp, select object string $no_component = `match "^[^\.]*" $objs[0]`; if($no_component != $objs[0]){ $objs = {}; $objs = `ls -l $no_component`; } //loop through each object, check if there's a symmetry, hardcoded as _r and _l for($o in $objs){ string $oSym = ($side)?(substituteAllString($o,"_r","_l")):(substituteAllString($o,"_l","_r")); if(`objExists $oSym` && ($oSym!=$o)){ string $cps[] = `ls -fl ($o+".cp[*]")`; int $sizeCP = size($cps); for($i=0;$i<$sizeCP;$i++){ int $mirroring = (`checkBox -q -v $cb`)?-1:1; $x = `getAttr($o+".controlPoints["+$i+"].xValue")`; $y = `getAttr($o+".controlPoints["+$i+"].yValue")`; $z = `getAttr($o+".controlPoints["+$i+"].zValue")`; setAttr ($oSym+".controlPoints["+$i+"].xValue") ($mirroring*$x); setAttr ($oSym+".controlPoints["+$i+"].yValue") ($mirroring*$y); setAttr ($oSym+".controlPoints["+$i+"].zValue") ($mirroring*$z); /*setAttr ($oSym+".controlPoints["+($sizeCP-$i)+"].xValue") ($x); setAttr ($oSym+".controlPoints["+($sizeCP-$i)+"].yValue") ($y); setAttr ($oSym+".controlPoints["+($sizeCP-$i)+"].zValue") ($z);*/ } }else{ warning("no "+(($side)?"left":"right")+" side found for "+$o); } } }
maxwell lock alphain gain bug
//sometimes maxwell is loaded in another scene (vray/arnold/mr) and fucks up the alpha gain (puts it at .5). So lock the alpha gainz for($t in `ls -typ "file"`){ print(catch(`setAttr -l true ($t+".ag")`)); }
maxwell shelf
global string $currentFrameFile; global string $error; $playblastActive = 0; $currentFrameFile = $error = ""; global proc firePlayblast(){ firePlayblastUI; } proc string findLayout( string $windowUI,string $name ) {//from bryan ewert string $controls[] = `lsUI -l -controlLayouts`; string $pattern = $windowUI + "*"; string $layout = ""; for ( $ui in $controls ) { if ( `gmatch $ui $pattern` ) { string $tokens[]; int $numTokens = `tokenize $ui "|" $tokens`; if ( $numTokens > 1 ) { $layout = $tokens[0] + "|" + $tokens[1]; string $ca[] = `layout -q -ca $layout`; for ( $c in $ca ) { return ($layout + "|" + $c); break; } break; } } } return false; } global proc string pad(float $n){return ($n<1000)? ( ($n<100 )?( ($n<10 )?"000"+$n:"00"+$n ):"0"+$n ) : $n+"";} global proc string getImagePath(string $extraPath,int $extension){ setAttr "defaultRenderGlobals.outFormatControl" 0; setAttr "defaultRenderGlobals.animation" 1; setAttr "defaultRenderGlobals.putFrameBeforeExt" 1; setAttr "defaultRenderGlobals.extensionPadding" 4; string $image = pad(`currentTime -q`); string $tof[] = `renderSettings -gin $image -fp`; string $dir = `match "^.*/" $tof[0]`; string $filepart = `match "[^/\\]*$" $tof[0]`; $filepart = (!$extension)?`match "(.*)[^\.a-z]" $filepart`:$filepart; return $dir+$extraPath+$filepart; } global proc string saveFireImage(int $openExplorer){ global string $error; global string $currentFrameFile; string $r; $filePath = getImagePath("maxwellFirePlayblasts/",0)+".png"; $mkdir = `sysFile -makeDir (match("^.*/",$filePath))`; string $vp = findLayout("MaxwellFIRE","maxwellViewport" ); if($mkdir && $vp != "0"){ maxwellViewport -e -saveIRImg ($filePath) $vp; $currentFrameFile = $filePath; $r = `toNativePath(match("^.*/",$filePath))`; if($openExplorer){ system("start explorer " + $r); }else{ maxwellSendIrImageToRV $vp; renderWindowMenuCommand keepImageInRenderView renderView; } }else{ $error = "No maxwell FIRE window found"; $r = $error; } return $r; } saveFireImage(0);
rolex
auto trotteuse
# utilisation: chopper un (ou plusieurs) objet ou un controlleur # eventuellement renommer attr= "rotateY" avec un autre axe # par defaut le tour se fait dans le sens des aiguilles d'une montre =), changer rotateDirection en 1.0 pour avoir l'inverse # 'offset' et 'cadence' modifiable sur lobjet import maya.cmds as mc attr = 'rotateY' rotateDirection = -1.0 for o in mc.ls(sl=1): mc.addAttr(o,longName='offsetSecondes', defaultValue=0.0) mc.setAttr(o+'.offsetSecondes', keyable=1) mc.addAttr(o,longName='cadenceHertz', defaultValue=8) mc.setAttr(o+'.cadenceHertz', keyable=1) expressionString = o+'.'+attr+' = '+str(rotateDirection)+'*('+o+'.offsetSecondes + floor(time*'+o+'.cadenceHertz)/'+o+'.cadenceHertz) * 6'; mc.expression(o+'.'+attr,s=expressionString)
misc
$ct = `currentTime -q`; currentTime -e 0; source channelBoxCommand; CBdeleteConnection "_montre_Submariner:MOD_verre1.tx"; CBdeleteConnection "_montre_Submariner:MOD_verre1.ty"; CBdeleteConnection "_montre_Submariner:MOD_verre1.tz"; CBdeleteConnection "_montre_Submariner:MOD_verre1.rx"; CBdeleteConnection "_montre_Submariner:MOD_verre1.ry"; CBdeleteConnection "_montre_Submariner:MOD_verre1.rz"; CBdeleteConnection "_montre_Submariner:MOD__montre_Submariner_submarine_obj31.tx"; CBdeleteConnection "_montre_Submariner:MOD__montre_Submariner_submarine_obj31.ty"; CBdeleteConnection "_montre_Submariner:MOD__montre_Submariner_submarine_obj31.tz"; CBdeleteConnection "_montre_Submariner:MOD__montre_Submariner_submarine_obj31.rx"; CBdeleteConnection "_montre_Submariner:MOD__montre_Submariner_submarine_obj31.ry"; CBdeleteConnection "_montre_Submariner:MOD__montre_Submariner_submarine_obj31.rz"; CBdeleteConnection "_montre_Submariner:MOD_trottinette.tx"; CBdeleteConnection "_montre_Submariner:MOD_trottinette.ty"; CBdeleteConnection "_montre_Submariner:MOD_trottinette.tz"; parentConstraint -mo -weight 1 _montre_Submariner:MOD_trottinette _montre_Submariner:MOD_verre1; parentConstraint -mo -weight 1 _montre_Submariner:MOD_trottinette _montre_Submariner:MOD__montre_Submariner_submarine_obj31; currentTime -e $ct; select -r "_montre_Submariner:MOD__montre_Submariner_submarine_obj31" "_montre_Submariner:MOD_verre1"; string $kf[] = `select -r "*:MOD_trottinette_rotateY"`; for($o in `ls -sl`){ $fc = `keyframe -query -keyframeCount $o`; $s = `keyframe -in 0 -q -tc $o`; $sV = `keyframe -in 0 -q -vc $o`; $e = `keyframe -in ($fc-1) -q -tc $o`; $eV = `keyframe -in ($fc-1) -q -vc $o`; int $start = $s[0]; int $end = $e[0]; float $base = $sV[0]; float $range = $eV[0]-$sV[0]; for($i=$start;$i<=$end;$i++){ float $step = $i - $start; float $totalTime = $end - $start; float $progression = (floor($step/3.125)*3.125) / $totalTime; float $kv = $base + $range * $progression; keyframe -e -a -vc $kv -t $i $o; } } select -r "_montre_Submariner:MOD__montre_Submariner_submarine_obj31" "_montre_Submariner:MOD_verre1" "*:MOD_trottinette";