SyntaxHighlighter

2016年9月15日木曜日

setProjectRootSettings

import nuke,nukescripts

def setProjectRootSettings():
    #
    setProjectFps = nuke.root()['fps'].setValue(30)
    #
    def largeFormat():
        sn = nuke.selectedNode()
        if sn.Class() != 'Read':
            print('#[WARNING]: リードノードが選択されてません')
            normalFormat()
        else:
            targetSizeFormat        = nuke.selectedNode().knob("format").value()
            sizeFormatWidth         = targetSizeFormat.width()
            sizeFormatHeight        = targetSizeFormat.height()
            sizeFormatPixelAspect   = targetSizeFormat.pixelAspect()
            hogehogeLarge               = str(sizeFormatWidth) + " " + str(sizeFormatHeight) + " " + str(sizeFormatPixelAspect) + " " + "hogehoge(large)"
            nuke.addFormat( hogehogeLarge )
            nuke.root()['format'].setValue("hogehoge(large)")
            setProjectFps

    def normalFormat():
        hogehogeNormalSize = '2520 1418 hogehoge(normal)'
        nuke.addFormat( hogehogeNormalSize )
        nuke.root()['format'].setValue("hogehoge(normal)")
        setProjectFps

    nodeSelected = nuke.nodesSelected()
    #print nodeSelected
    if nodeSelected == False:
        normalFormat()
    else:
        largeFormat()

setProjectRootSettings()

2015年12月29日火曜日

openDirectory


var currentDate         = dateAcquisition()[0] +"_"+ dateAcquisition()[1] +"_"+ dateAcquisition()[2] ;
var currentTime         = dateAcquisition()[3] +"_"+ dateAcquisition()[4];
//カレントのAepファイルのパス "-project project_path"
var aepProjectFileAbsolutePath  = app.project.file.absoluteURI;
//カレントのAepファイルのバージョン
var aepFileVersion              = fileNameVersionExtension(aepProjectFileAbsolutePath)[4];
//年月日取得
function dateAcquisition() {
  //今日の日時示
  var now   = new Date();
  var year  = now.getYear();      // 年
  var month = now.getMonth() + 1; // 月
  var day   = now.getDate();      // 日
  var hour  = now.getHours();     // 時
  var min   = now.getMinutes();   // 分
  var sec   = now.getSeconds();   // 秒
  if(year < 2000) { year += 1900; }
  // 数値が1桁の場合、頭に0を付けて2桁で表示する指定
  if(month  < 10) { month = "0" + month; }
  if(day    < 10) { day   = "0" + day; }
  if(hour   < 10) { hour  = "0" + hour; }
  if(min    < 10) { min   = "0" + min; }
  if(sec    < 10) { sec   = "0" + sec; }
  return [ year , month , day , hour , min , sec ];
}
//ファイル名と拡張子とバージョン取得
function fileNameVersionExtension(AbsolutePath) {
  //拡張子込ファイル名
  var filePathAry           = AbsolutePath.split("/");
  var filePathAryLength     = filePathAry.length -1;
  var fileFullName          = filePathAry[filePathAryLength];
  //ファイル名とファイルタイプ(拡張子)
  var fileNameAry           = fileFullName.split(".");
  var fileNameAryLength     = fileNameAry.length -1;
  var fileName              = fileNameAry[0];
  var fileExtension         = fileNameAry[fileNameAryLength];
  //ファイルネーム要素
  var fileNameElement       = fileName.split("_");
  var fileVersionAryLength  = fileNameElement.length -1;
  var fileVersion           = fileNameElement[fileVersionAryLength];
  return [fileFullName , fileName , fileExtension , fileNameElement , fileVersion ];
}

function openDirectory() {
  var aepPathObj            = new Folder(app.project.file.path);

  var imagesDir             = app.project.file.path +"/"+ "images";
  var imagesDirObj          = new Folder( imagesDir );
  var outputDir             = app.project.file.path +"/"+ "images" +"/"+ aepFileVersion;
  var outputDirObj          = new Folder( outputDir );

  var userTempDirObj        = new Folder ( Folder.temp) ;
  var aerenderDir           = (userTempDirObj.toString() + "/afterEffect/aerender/");
  var aerenderDirObj        = new Folder( aerenderDir );
  var aeBatDir              = (userTempDirObj.toString() + "/afterEffect/aerender/batch/");
  var aeBatchDirObj         = new Folder( aeBatDir );
  var aeTodayBatchDirObj    = new Folder( aeBatDir + currentDate );
  var aepDir                = (userTempDirObj.toString() + "/afterEffect/aerender/project/");
  var aepDirObj             = new Folder( aepDir );
  var aepTodayDirObj        = new Folder( aepDir + currentDate );
  return [ aepPathObj , imagesDirObj , outputDirObj , userTempDirObj , aerenderDirObj , aeBatchDirObj , aeTodayBatchDirObj , aepDirObj , aepTodayDirObj];
}

function openAepCopyDir() {
  if (openDirectory()[8].exists == true) {
    openDirectory()[8].execute();
  }else {
    if (openDirectory()[7].exists == true) {
      openDirectory()[7].execute();
    }else {
      if (openDirectory()[4].exists == true) {
        openDirectory()[4].execute();
      }else {
        if (openDirectory()[3].exists == true) {
          openDirectory()[3].execute();
        }else {
          alert("ないっす!!!((((;゚Д゚))))ガクガクブルブル");
        }
      }
    }
  }
}

function openAepBatDir() {
  if (openDirectory()[6].exists == true) {
    openDirectory()[6].execute();
  }else {
    if (openDirectory()[5].exists == true) {
      openDirectory()[5].execute();
    }else {
      if (openDirectory()[4].exists == true) {
        openDirectory()[4].execute();
      }else {
        if (openDirectory()[3].exists == true) {
          openDirectory()[3].execute();
        }else {
          alert("ないっす!!!((((;゚Д゚))))ガクガクブルブル");
        }
      }
    }
  }
}

function openImagesDir() {
  if (openDirectory()[2].exists == true) {
    openDirectory()[2].execute();
  }else {
    if (openDirectory()[1].exists == true) {
      openDirectory()[1].execute();
    }else {
      if (openDirectory()[0].exists == true) {
        openDirectory()[0].execute();
      }else {
        alert("ないっす!!!((((;゚Д゚))))ガクガクブルブル");
      }
    }
  }
}

function openAepDir() {
  if (openDirectory()[0].exists == true) {
    openDirectory()[0].execute();
  }else {
    alert("ないっす!!!((((;゚Д゚))))ガクガクブルブル");
  }
}

function inputPromptOpenDirectory() {
  var selectChoice = prompt("0-2を入力してください\n"+
                    "0:カレントAEPファイルのフォルダを開く\n"+
                    "1:カレントイメージフォルダを開く\n"+
                    "2:バッチファイルフォルダを開く"
                    ,"0"
                    ,"OpenDirectory");
  if (selectChoice != null) {
    if (selectChoice == 0) {
      openAepDir();
    }else if (selectChoice == 1) {
      openImagesDir();
    }else if (selectChoice == 2) {
      openAepBatDir();
    }else if (selectChoice == 3) {
      openAepCopyDir();
    }else {
      alert("むりっす:-p");
    }
  }else {
    alert("キャンセルされました");
  }
}
inputPromptOpenDirectory()

2015年12月27日日曜日

setRenderOutput

レンダーキューでアクティブなキューの設定をする(ディレクトリも作成)

//年月日取得
function dateAcquisition(){
  //今日の日時示
  var now   = new Date();
  var year  = now.getYear();      // 年
  var month = now.getMonth() + 1; // 月
  var day   = now.getDate();      // 日
  var hour  = now.getHours();     // 時
  var min   = now.getMinutes();   // 分
  var sec   = now.getSeconds();   // 秒
  if(year < 2000) { year += 1900; }
  // 数値が1桁の場合、頭に0を付けて2桁で表示する指定
  if(month  < 10) { month = "0" + month; }
  if(day    < 10) { day   = "0" + day; }
  if(hour   < 10) { hour  = "0" + hour; }
  if(min    < 10) { min   = "0" + min; }
  if(sec    < 10) { sec   = "0" + sec; }
  return [ year , month , day , hour , min , sec ];
}
//ファイル名と拡張子とバージョン取得
function fileNameVersionExtension(AbsolutePath){
  //拡張子込ファイル名
  var filePathAry           = AbsolutePath.split("/");
  var filePathAryLength     = filePathAry.length -1;
  var fileFullName          = filePathAry[filePathAryLength];
  //ファイル名とファイルタイプ(拡張子)
  var fileNameAry           = fileFullName.split(".");
  var fileNameAryLength     = fileNameAry.length -1;
  var fileName              = fileNameAry[0];
  var fileExtension         = fileNameAry[fileNameAryLength];
  //ファイルネーム要素
  var fileNameElement       = fileName.split("_");
  var fileVersionAryLength  = fileNameElement.length -1;
  var fileVersion           = fileNameElement[fileVersionAryLength];
  return [fileFullName , fileName , fileExtension , fileNameElement , fileVersion ];
}
//コマンドラインオプション
function commandLineOption(i){
  //コンポジション名 "-comp comp_name"
  var compositonName              = app.project.renderQueue.item(i).comp.name;
  //コンポジションのフレームレート
  var compositonFrameRate         = app.project.renderQueue.item(i).comp.frameRate;
  //コンポジションのデュレーション
  var compositonDuration          = app.project.renderQueue.item(i).comp.duration * compositonFrameRate;
  //コンポジションのスタートフレーム "-s start_frame"
  var compostionStartTime         = app.project.renderQueue.item(i).comp.displayStartTime * compositonFrameRate;
  //コンポジションのエンドフレーム "-e end_frame"
  var compostionEndTime           = (compostionStartTime + compositonDuration) - 1;
  //ワークエリアのスタートフレーム "-s start_frame"
  var compostionWorkAreaStart     = app.project.renderQueue.item(i).comp.workAreaStart * compositonFrameRate;
  //ワークエリアのデュレーション
  var compositonWorkAreaDuration  = app.project.renderQueue.item(i).comp.workAreaDuration * compositonFrameRate;
  //コンポジションのエンドフレーム "-e end_frame"
  var compostionWorkAreaEndTime   = (compostionWorkAreaStart + compositonWorkAreaDuration) - 1;
  //レンダリング出力先 "-output  output_path"
  var renderPath                  = app.project.renderQueue.item(i).outputModule(1).file;
  //レンダリング出力先その2 ※Absoluteをつけないと配列にならない
  var renderAbsolutePath          = app.project.renderQueue.item(i).outputModule(1).file.absoluteURI;
  return [ compositonName , compostionStartTime , compostionEndTime , compostionWorkAreaStart , compostionWorkAreaEndTime , renderAbsolutePath ]
}
//コンプレイヤネーム
function compostionLayerName(i){
  var compositonName      = commandLineOption(i)[0];
  var compNameElement     = compositonName.split("_");
  var compNameAryLength   = compNameElement.length -1;
  var compLayerName       = compNameElement[compNameAryLength];
  return [ compLayerName ];
}
//
function makeOutputDir(i){
  var compLayerName = compostionLayerName(i)[0];
  var folder        = app.project.file.path +"/"+ "images" +"/"+ aepFileVersion  +"/"+ compLayerName;
  folderObj = new Folder(folder);
  folderObj.create();
  return [ folder ];
}
//
function setRenderOutput(i,selectChoice){
  //パディング指定部分の文字列
  var frameCountPadding           = new RegExp("%5B#{1,7}%5D","i");
  //ムービもしくはサウンドファイルの拡張子の文字列
  var movieSoundFile              = new RegExp("(aif|avi|f4v|flv|mp4|m4v|mp3|mpg|mxf|mov|wav)$","i");
  //イメージファイルの拡張子文字列
  var sequenceImageFile           = new RegExp("dpx|cin|iff|jpg|exr|png|psd|hdr|sgi|tif|tga","i");
  var curRnedSet                  = app.project.renderQueue.item(i).outputModule(1);
  var renderAbsolutePath          = app.project.renderQueue.item(i).outputModule(1).file.absoluteURI;
  var fileNeme                    = fileNameVersionExtension(renderAbsolutePath);
  var renderOutputFolder          = makeOutputDir(i)[0];
  if (selectChoice == 0) {
    if ((frameCountPadding.test(fileNeme[0]) == 1)&&(sequenceImageFile.test(fileNeme[0]) == 1)) {
      curRnedSet.file = new File(renderOutputFolder +"/"+  fileNameSetImage );
    }
    else if ((frameCountPadding.test(fileNeme[0]) == 0)&&(sequenceImageFile.test(fileNeme[0]) == 1)) {
      curRnedSet.file = new File(renderOutputFolder +"/"+  fileNameSetImage );
    }
    else if (movieSoundFile.test(fileNeme[0]) == 1) {
      curRnedSet.file = new File(renderOutputFolder +"/"+  fileNameSetMovieSound );
    }
    //
  }else if (selectChoice == 1) {
    curRnedSet.applyTemplate(outputModuleProject);
    curRnedSet.file = new File(renderOutputFolder +"/"+  fileNameSetImage );
    //
  }else if (selectChoice == 2) {
    if ((frameCountPadding.test(fileNeme[0]) == 1)&&(sequenceImageFile.test(fileNeme[0]) == 1)) {
      curRnedSet.applyTemplate(outputModuleImage);
      curRnedSet.file = new File(renderOutputFolder +"/"+  fileNameSetImage );
    }
    else if ((frameCountPadding.test(fileNeme[0]) == 0)&&(sequenceImageFile.test(fileNeme[0]) == 1)) {
      curRnedSet.applyTemplate(outputModuleImage);
      curRnedSet.file = new File(renderOutputFolder +"/"+  fileNameSetImage );
    }
    else if (movieSoundFile.test(fileNeme[0]) == 1) {
      curRnedSet.applyTemplate(outputModuleMovieSound);
      curRnedSet.file = new File(renderOutputFolder +"/"+  fileNameSetMovieSound );
    }
  }else {
  }
}
//
function inputPromptSetRenderOutput(){
  var selectChoice = prompt("0-2を入力してください\n"+
                    "0:出力モジュールは変更せず出力先を設定\n"+
                    "1:出力モジュールを一括設定して出力先を設定!\n"+
                    "2:出力モジュールを設定して出力先を設定(ファイル判別)"
                    ,"0"
                    ,"setRenderPath");
  if (selectChoice != null){
    for (i = 1 ; i <= renderQueNumberItem ; i++){
        var renderQueActiveCompostion   = app.project.renderQueue.item(i).render;
        var renderAbsolutePath          = app.project.renderQueue.item(i).outputModule(1).file.absoluteURI;
        var fileNeme                    = fileNameVersionExtension(renderAbsolutePath);
        if (renderQueActiveCompostion == 1) {
          makeOutputDir(i);
          setRenderOutput(i,selectChoice);
        }
        else if(renderQueActiveCompostion == 0) {
          //alert("レンダーキューにアクティブなアイテムがねーっす:-q")
        }
    }
    if (selectChoice <= 2) {
      alert("設定しました");
    }else {
      alert("むりっす:-p");
    }
  }else {
    alert("キャンセルされました")
  }
}

//日時
var currentDate                 = dateAcquisition()[0] +"_"+ dateAcquisition()[1] +"_"+ dateAcquisition()[2] ;
//時刻
var currentTime                 = dateAcquisition()[3] +"_"+ dateAcquisition()[4];
//カレントのAepファイルのパス "-project project_path"
var aepProjectFileAbsolutePath  = app.project.file.absoluteURI;
//カレントのAepファイルの名前
var afterEffectsFileNeme        = fileNameVersionExtension(aepProjectFileAbsolutePath);
//レンダーキューのアイテム数
var renderQueNumberItem         = app.project.renderQueue.numItems;
//カレントのAepファイルのバージョン
var aepFileVersion              = fileNameVersionExtension(aepProjectFileAbsolutePath)[4];
//出力モジュール
var outputModuleImage           = "TIFF シーケンス (アルファ付き)"   //"Photoshop"
var outputModuleMovieSound      = "ロスレス圧縮(アルファ付き)"     //"H.264"
var outputModuleProject         = "Photoshop"                    //"TIFF シーケンス (アルファ付き)"
//ファイル名
var fileNameSetImage            = "[compName]_" + aepFileVersion + "_[####].[fileExtension]";
var fileNameSetMovieSound       = "[compName]_" + aepFileVersion + ".[fileExtension]";
inputPromptSetRenderOutput();

2015年12月24日木曜日

aerenderDiv

//aerender スキップフレーム版

var currentDate         = dateAcquisition()[0] +"_"+ dateAcquisition()[1] +"_"+ dateAcquisition()[2] ;
var currentTime         = dateAcquisition()[3] +"_"+ dateAcquisition()[4];
var randnum             = Math.floor( Math.random() * 100000 );
var userTempDir         = new Folder (Folder.temp);
//カレントのAepファイルのパス "-project project_path"
var aepProjectFileAbsolutePath  = app.project.file.absoluteURI;
//カレントのAepファイルの名前
var afterEffectsFileNeme        = fileNameExtension(aepProjectFileAbsolutePath);
//カレントaerenderのファイルのパス
var aeRenderAbsolutePath        = '"C:\\Program Files\\Adobe\\Adobe After Effects '+ applicationVersion() +'\\Support Files\\aerender.exe"';
//レンダーキューのアイテム数
var renderQueNumberItem         = app.project.renderQueue.numItems
//メモリの使用量とキャッシュの使用量 "-mem_usage image_cache_percent max_mem_percent"

//年月日取得
function dateAcquisition(){
  //今日の日時示
  var now   = new Date();
  var year  = now.getYear();      // 年
  var month = now.getMonth() + 1; // 月
  var day   = now.getDate();      // 日
  var hour  = now.getHours();     // 時
  var min   = now.getMinutes();   // 分
  var sec   = now.getSeconds();   // 秒
  if(year < 2000) { year += 1900; }
  // 数値が1桁の場合、頭に0を付けて2桁で表示する指定
  if(month  < 10) { month = "0" + month; }
  if(day    < 10) { day   = "0" + day; }
  if(hour   < 10) { hour  = "0" + hour; }
  if(min    < 10) { min   = "0" + min; }
  if(sec    < 10) { sec   = "0" + sec; }
  return [ year , month , day , hour , min , sec ];
}
//afterEffectsの確認
function applicationVersion(){
  var applicationBuildNumber  = app.buildName;
  var applicationVersion      = applicationBuildNumber.substring(0,4);
  if (applicationVersion == 10.0) {
    var applicationVersionCharacter = "CS5";
    return applicationVersionCharacter;
  }else if (applicationVersion == 10.5){
    var applicationVersionCharacter = "CS5.5";
    return applicationVersionCharacter;
  }else if ((applicationVersion == 11.0)||(applicationVersion == 11.1)){
    var applicationVersionCharacter = "CS6";
    return applicationVersionCharacter;
  }else if ((applicationVersion == 13.0)||(applicationVersion == 13.1)){
    var applicationVersionCharacter = "CC 2014";
    return applicationVersionCharacter;
  }else{
    return "バージョンを確認してください";
  }
}
//ファイル名と拡張子取得
function fileNameExtension(AbsolutePath){
  //拡張子込ファイル名
  var filePathAry           = AbsolutePath.split("/");
  var filePathAryLength     = filePathAry.length -1;
  var fileFullName          = filePathAry[filePathAryLength];
  //ファイル名とファイルタイプ(拡張子)
  var fileNameAry           = fileFullName.split(".");
  var fileNameAryLength     = fileNameAry.length -1;
  var fileName              = fileNameAry[0];
  var fileExtension         = fileNameAry[fileNameAryLength];
  return [fileFullName , fileName , fileExtension];
}
//プロジェクトファイルをtempへコピー
function copyAepFileToTemp(copySourceAep,copyDestinationDir){
  var currentAepFile              = new File( copySourceAep );
  var copyAepFile                 = new File( afterEffectsProjDir + currentDate +"/"+ afterEffectsFileNeme[0] );
  currentAepFile.copy(copyAepFile);
}
//ログファイル書き出し先 "-log logfile_path"
function createPathAepLogDir(){
  var afterEffectsLogDir          = (userTempDir.toString() + "/afterEffect/aerender/log/" + currentDate);
  var createAfterEffectsLogDir    = new Folder( afterEffectsLogDir ).create();
  return [ createAfterEffectsLogDir , afterEffectsLogDir ];
}
//プロジェクトファイルコピー先
function createPathAepProjDir(){
  var afterEffectsProjDir         = (userTempDir.toString() + "/afterEffect/aerender/project/");
  var createAfterEffectsAepDir    = new Folder( afterEffectsProjDir + currentDate ).create();
  return [ createAfterEffectsAepDir , afterEffectsProjDir ];
}
//バッチファイル書き出し先
function createPathAepBatDir(){
  var afterEffectsBatDir          = (userTempDir.toString() + "/afterEffect/aerender/batch/");
  var createAfterEffectsBatDir    = new Folder( afterEffectsBatDir + currentDate ).create();
  return [ createAfterEffectsBatDir , afterEffectsBatDir ];
}
//バッチファイル作成
function createPathBatchFile(afterEffectsBatDir){
  var afterEffectsBatFileName     = ("aerender" +"_" + afterEffectsFileNeme[1] +"_" + currentTime +"_"+ randnum + ".bat");
  var afterEffectsBatFilePath     = afterEffectsBatDir + currentDate +"/"+ afterEffectsBatFileName;
  var afterEffectsBatFile         = new File( afterEffectsBatFilePath );
  return [ afterEffectsBatFile , afterEffectsBatFilePath , afterEffectsBatFileName ];
}
//バッチファイルにコマンド追記
function addCommandToBatchFile(afterEffectsBatFile){
  var batFile =  new File(afterEffectsBatFile);
  var aepFileName = fileNameExtension(aepProjectFileAbsolutePath)[0];
  batFile.open("w");
  batFile.writeln("@echo off");
  batFile.writeln("title" +" "+ aepFileName +" "+ applicationVersion() +" "+ "batch start at"+" "+  "%time%");
  for  ( i = 0; i < batCommandLineAry.length; i++){
      batFile.writeln(batCommandLineAry[i]) + "\n";
  }
  batFile.close();
}
//コマンドラインオプション
function commandLineOption(i){
  //コンポジション名 "-comp comp_name"
  var compositonName              = app.project.renderQueue.item(i).comp.name;
  //コンポジションのフレームレート
  var compositonFrameRate         = app.project.renderQueue.item(i).comp.frameRate;
  //コンポジションのデュレーション
  var compositonDuration          = app.project.renderQueue.item(i).comp.duration * compositonFrameRate;
  //コンポジションのスタートフレーム "-s start_frame"
  var compostionStartTime         = app.project.renderQueue.item(i).comp.displayStartTime * compositonFrameRate;
  //コンポジションのエンドフレーム "-e end_frame"
  var compostionEndTime           = (compostionStartTime + compositonDuration) - 1;
  //ワークエリアのスタートフレーム "-s start_frame"
  var compostionWorkAreaStart     = app.project.renderQueue.item(i).comp.workAreaStart * compositonFrameRate;
  //ワークエリアのデュレーション
  var compositonWorkAreaDuration  = app.project.renderQueue.item(i).comp.workAreaDuration * compositonFrameRate;
  //コンポジションのエンドフレーム "-e end_frame"
  var compostionWorkAreaEndTime           = (compostionWorkAreaStart + compositonWorkAreaDuration) - 1;
  //レンダリング出力先 "-output  output_path"
  var renderPath                  = app.project.renderQueue.item(i).outputModule(1).file;
  //レンダリング出力先その2 ※Absoluteをつけないと配列にならない
  var renderAbsolutePath          = app.project.renderQueue.item(i).outputModule(1).file.absoluteURI;
  return [ compositonName , compostionStartTime , compostionEndTime , compostionWorkAreaStart , compostionWorkAreaEndTime , renderAbsolutePath ]
}
//分割しない場合のコマンドライン
function indivisibleFileComandLine(i){
  var comp = commandLineOption(i)[0];
  var indivisibleFile = "start /wait"
    +" "+ '"' + comp +" "+ applicationVersion() +" "+ "rendering start at"+" "+ "%time%"+'"'
    +" "+ aeRenderAbsolutePath
    +" "+ "-project" + " " + aepProjectFileAbsolutePath
    +" "+ "-rqindex" + " " + i
    +" "+ "-sound ON"
    +" "+ "-continueOnMissingFootage";
  batCommandLineAry.push(indivisibleFile);
}
//分割する場合のコマンドライン
function divideFileComandLine(i){
  var comp = commandLineOption(i)[0];
  var divideNum = numDiv
  for (k = 1 ; k <= divideNum ; k++){
    if (k < divideNum) {
      var indivisibleFile = "start"
        +" "+ '"' + comp +" "+ applicationVersion() +" "+ "rendering start at"+" "+ "%time%"+'"'
        +" "+ aeRenderAbsolutePath
        +" "+ "-project" + " " + aepProjectFileAbsolutePath
        +" "+ "-rqindex" + " " + i
        +" "+ "-RStemplate" + " " + "マルチマシン設定"
        +" "+ "-continueOnMissingFootage";
        batCommandLineAry.push(indivisibleFile);
    }else if (k == divideNum) {
      var indivisibleFile = "start /wait"
        +" "+ '"' + comp +" "+ applicationVersion() +" "+ "rendering start at"+" "+ "%time%"+'"'
        +" "+ aeRenderAbsolutePath
        +" "+ "-project" + " " + aepProjectFileAbsolutePath
        +" "+ "-rqindex" + " " + i
        +" "+ "-RStemplate" + " " + "マルチマシン設定"
        +" "+ "-sound ON"
        +" "+ "-continueOnMissingFootage";
        batCommandLineAry.push(indivisibleFile);
    }else {
      batCommandLineAry.push(":-q")
    }
  }
}
//レンダーキューのアクティブキュー情報取得バッチファイルへ書き出し
function renderQueueToBatchFile(){
  //パディング指定部分の文字列
  var frameCountPadding           = new RegExp("%5B#{1,7}%5D","i");
  //ムービもしくはサウンドファイルの拡張子の文字列
  var movieSoundFile              = new RegExp("(aif|avi|f4v|flv|mp4|m4v|mp3|mpg|mxf|mov|wav)$","i");
  //イメージファイルの拡張子文字列
  var sequenceImageFile           = new RegExp("dpx|cin|iff|jpg|exr|png|psd|hdr|sgi|tif|tga","i");
  
  for (i = 1 ; i <= renderQueNumberItem ; i++){
      var renderQueActiveCompostion   = app.project.renderQueue.item(i).render;
      var renderAbsolutePath          = app.project.renderQueue.item(i).outputModule(1).file.absoluteURI;
      var fileNeme                    = fileNameExtension(renderAbsolutePath);
      if (renderQueActiveCompostion == 1) {
          //alert (fileNeme[0] + "を" +"レンダーするっす:-p");
          if ((frameCountPadding.test(fileNeme[0]) == 1)&&(sequenceImageFile.test(fileNeme[0]) == 1)) {
            if (numDiv == 0){
              //alert("レンダリングしないっす:-q");
            }else if (numDiv == 1) {
              //alert("レンダリングするっす:-q");
              indivisibleFileComandLine(i);
            }else if (numDiv >= 2 && numDiv <= 12) {
              //alert("レンダリングするっす:-q");
              divideFileComandLine(i);
            }
          }
          else if ((frameCountPadding.test(fileNeme[0]) == 0)&&(sequenceImageFile.test(fileNeme[0]) == 1)) {
              indivisibleFileComandLine(i);
          }
          else if (movieSoundFile.test(fileNeme[0]) == 1) {
              indivisibleFileComandLine(i);
          }
      }
      else if(renderQueActiveCompostion == 0) {
      //alert ("レンダーキューにアクティブなアイテムがねーっす:-q")
      }
  }
}
//入力ダイアログ
function inputPrompt(){
  var text = prompt("並列でレンダリングする数を入力してください \n 2-8 をお勧めします","4");
  if (text != null){
    //alert("並列数は"+text+"です")
  }else {
    alert("キャンセルされました")
  }
  return [ text ];
}
//レンダリング条件分岐
function renderingBranch(){
  if (numDiv == 0){
    alert("レンダリングしないっす:-q");
  }else if (numDiv == 1) {
    renderQueueToBatchFile();
    createBatchFile;
    addCommandToBatchFile(afterEffectsBatFile);
    alert("並列レンダリングしないっす:-q");
  }else if (numDiv >= 2 && numDiv <= 8) {
    renderQueueToBatchFile();
    createBatchFile;
    addCommandToBatchFile(afterEffectsBatFile);
    alert("並列レンダリングするっす:-D");
  }else if (numDiv >= 9 && numDiv <= 12) {
    renderQueueToBatchFile();
    createBatchFile;
    addCommandToBatchFile(afterEffectsBatFile); 
    alert("お勧めしないぴょん:-p");
  }else if (numDiv >= 13) {
    alert("むりっす(;´・ω・)");
  }
}
//メイン
var numDiv = inputPrompt()[0];
var batCommandLineAry   = new Array();
var afterEffectsBatFile = createPathBatchFile(createPathAepBatDir()[1])[1];
var batFile =  new File(afterEffectsBatFile);
var createBatchFile     = createPathBatchFile(createPathAepBatDir()[1]);

renderingBranch();
batFile.execute();

2015年10月2日金曜日

nuke_memo

root関係めも


nuke.root()['format'].setValue("HD")
nuke.root()['format'].setValue( "square_2K" )

scriptFormats = nuke.formats()

for f in scriptFormats:
print f.name()
print f.width()
print f.height()
print f.pixelAspect()

print 10*'-'


nuke.root()['format'].value().name() # renvoi le nom du format
nuke.root()['format'].value().setName("nomDuFormat")


print nuke.root()['format'].value().width()
print nuke.root()['format'].value().height()
print nuke.root()['format'].value().pixelAspect()

print nuke.root()['format'].value().name()



square2k = '2048 2048 square 2k'
nuke.addFormat( square2k )

nuke.root()['format'].setValue(nuke.addFormat("1024 960 1")) 



quare2k = '2048 2048 square 2k'
nuke.addFormat( square2k )
nuke.root()[‘format’].setValue( ‘square 2k’ )

# DEFINE BASE AND PROXY FORMATS
square2k = '2048 2048 square 2k'
square1k = '1024 1024 square 1k'

# ADD FORMATS TO SESSION
for f in ( square2k, square1k ):
nuke.addFormat( f )

# SET THE ROOT TO USE BOTH BASE AND PROXY FORMATS
root = nuke.root()
root['format'].setValue( 'square 2k' )
root['proxy_type'].setValue( 'format' )

root['proxy_format'].setValue( 'square 1k' )

2015年10月1日木曜日

選んだオブジェクトにロケータをペアレントコンストレイントしてベイク


選んだオブジェクトにロケータをペアレントコンストレイントしてベイク


proc BakeLocator(){
 
string $Selobjs[] =`ls -sl -tr`;
int $Selsum = `size( $Selobjs )`;
//print $Selsum;
string $addStr = "_nukeLightLoc";
string $tagStr = "hoge";
string $repStr = "hogehoge";
string $conStr = "_parentConstraint1";
//print ($addStr + "," + $tagStr + "," + $repStr + "," + $conStr);
int $x;

for($x = 0; $x < $Selsum; $x++ ){
    CreateLocator;                
    string $LocSelA[] = `ls -sl`;  
 
    select $Selobjs[$x];
    string $RnmLoc = (substituteAllString($Selobjs[$x], $tagStr , $repStr )) + $addStr ;
    string $rnmObj = `rename $LocSelA[0] $RnmLoc`;
 
    select -r $Selobjs[$x] $rnmObj;
//ペアレントコンストレイントコマンド
    doCreateParentConstraintArgList 1 { "0","0","0","0","0","0","0","1","","1" };
    parentConstraint -weight 1;
    print($rnmObj + $conStr);
}
select -r ("*" + $addStr);
string $SelLocs[] =`ls -sl -tr`;
int $SelLocSum = `size( $SelLocs )`;

string $sFrame =`playbackOptions -query -minTime`;
string $eFrame =`playbackOptions -query -maxTime`;
string $bRange = ($sFrame + ":" + $eFrame);
//print $bRange;
bakeSimulation -t $bRange -at "tx" -at "ty" -at "tz" -at "rx" -at "ry" -at "rz";
select -r ("*" + $addStr + $conStr);
delete;
}
BakeLocator();

2015年7月13日月曜日

メモ_nuke

忘れないように...(^^;

上流のノード取得
for n in node.dependencies()

下流のノード取得
for n in node.dependent()

2015年7月2日木曜日

カレントディレクトリ等をExplorerで開くmel

カレントディレクトリ等を開くmel
数字でオープン先を選ぶ

global proc sDirOpen()
{  
    //-----------------------------------------------------------------------------------------------------
    string $fPath = `file -q -sceneName`;
    string $fName = `file -q -shortName -sceneName`;
    string $sPath = substituteAllString($fPath, $fName , "");
    string $iPath = substituteAllString($sPath, "scenes/"  , "images/");
    string $itPath = substituteAllString($sPath, "scenes/"  , "images/tmp/");
    //-----------------------------------------------------------------------------------------------------
    string $text;
    string $result = `promptDialog
        -title "sDirOpen"
        -message "input Number:"
        -text "0"
        -button "OK" -button "Cancel"
        -defaultButton "OK" -cancelButton "Cancel"
        -dismissString "Cancel"`;

    if ($result == "OK")
    {
        $text = `promptDialog -query -text`;
        if($text == 0)
        {
        print ($sPath + "\n");
        string $sOsPath = substituteAllString($sPath, "/", "\\");
        print ($sOsPath+ "\n");
        system ("explorer.exe "+ $sOsPath);
        }
        else if($text == 1)
        {
        print ($iPath + "\n");
        string $iOsPath = substituteAllString($iPath, "/", "\\");
        system ("explorer.exe "+ $iOsPath);
        }
        else if($text == 2)
        {
        string $itOsPath = substituteAllString($itPath, "/", "\\");
        system ("explorer.exe "+$itOsPath);  
        }
        else
        {
        string $window = `window -title "alart"
        -iconName "Short Name"
        -widthHeight 64 24`;
        columnLayout -adjustableColumn true;
            button -label "ねーっす :-P" -command ("deleteUI -window " + $window);
            setParent ..;
            showWindow $window;
        //print "ねーっす";
        }
    }
}
sDirOpen()

2015年4月1日水曜日

カレントディレクトリをExplorerで開く

別アプリで書かれていたものを丸パクリしたもの

import nuke
import os.path
import sys
def openCurrent():
path = nuke.root().name()
if path == 'Root':
print('#[WARNING]: No scene is opened.')
return
nkp = '\\'.join(path.split('/')[:-1])
if os.path.isdir(nkp):
os.popen('explorer "%s"' % nkp)
print('>> Open: %s' % nkp)
else:
print('#[WARANING]: Directory not found: %s' % nkp)
openCurrent()

<pre class="brush: python;">
// ココにソースを記述
</pre>

2015年3月11日水曜日

nukeでコマ落とし

コマ落としとバレ消しの注意書き

import nuke

readNodes = nuke.allNodes("Read")
for node in nuke.allNodes():
    node["selected"].setValue(0)
    #print node
for read in readNodes:
    read["selected"].setValue(1)
    first = read["first"].getValue()
    last  = read["last"].getValue()

    timeWarp = nuke.createNode("TimeWarp")
    timeWarp["lookup"].setAnimated(0)
    timeWarp["lookup"].animations()[0].setKey(first, first)
    timeWarp["lookup"].animations()[0].setKey(last, last)
    if first%2 == 0:
        timeWarp["lookup"].setExpression('(int(curve/2))*2')
    else:
        timeWarp["lookup"].setExpression('((int((curve+1)/2))*2)-1')      
    NoteOfCaution = nuke.nuke.createNode("Text2")
    NoteOfCaution["message"].setValue('バレ消しの必要はありません')
    NoteOfCaution["font"].setValue("Adobe Gothic Std", "B")
    NoteOfCaution["font_size"].setValue(72)
    if first%2 == 0:
        NoteOfCaution["opacity"].setExpression('(frame%2)')
    else:
        NoteOfCaution["opacity"].setExpression('((frame+1)%2)')

    read["selected"].setValue(0)
    timeWarp["selected"].setValue(0)
    NoteOfCaution["selected"].setValue(0)

2014年8月21日木曜日

メモ_maya(選択したオブジェクトのアトリビュートを変更)

他のページからのコピペ

選択したオブジェクトのアトリビュートを変更

string $obj[] = `ls -sl`;

for ($objSel in $obj)
{
//変更可能なのは、ここから//
setAttr ($objSel+".miReflectionBlur") 2.5;
//ここまで//
}

-------------------------------------------------------
これは、「選択したマテリアルにリフレクションブラーを入れる」ってこと

1.//「for ($objSel in $obj)」は、「$objの中の$objSel」を//
2.//setAttr ($objSel+".miReflectionBlur") 2.5;しますって意味//
3.「2.5」って数値は、リフレクションブラーを2.5にしますって意味。
----------------------------------------------------------------------

つまり、2の「.miReflectionBlur」の中身を変えれば、どんなものでも一括で変更できる。また、1行だけでなく何行入れてもいい。

たとえば、
@選択したマテリアルを全てブラックホールにする。
setAttr ($objSel+".matteOpacityMode") 0;

@選択したマテリアルを全てブラックホールをやめる。
setAttr ($objSel+".matteOpacityMode") 2;

@選択したマテリアルを全てグローを切る。
setAttr ($objSel+".glowIntensity") 0;

@選択したマテリアルのambientColorに、occlusionをつける。
connectAttr -force mib_amb_occlusion1.outValue ($objSel+".ambientColor");
//「mib_amb_occlusion1」は、オクルージョンの名前//



---------------------------------------------------------------------------------------------
//選んだカメラのアトリビュートを変更

string $obj[] = `ls -sl`;
for($lsCam in $obj)
{
setAttr($lsCam+".filmFit")1;
setAttr($lsCam+".cameraScale")1.2;
}
---------------------------------------------------------------------------------------------
//
マニピュレータをオンにする

string $slCam[] = `ls -sl`;
for($lsCam in $slCam)
{
renderManip -e -cam 0 0 0 1 0 $lsCam ;
}

---------------------------------------------------------------------------------------------

string $pMesh[] = `ls -type "mesh"`;
//select $pMesh;
for ($spMesh in $pMesh)
{
    print ($spMesh + "\n");
    setAttr ($spMesh + ".overrideEnabled")0;
    //setAttr ($spMesh + ".template")0;
}
---------------------------------------------------------------------------------------------
//カメラのイメージプレーンを削除
string $list[] = `lsType imagePlane`;
for ($node in $list)
{
select -r $node;
delete;
}
---------------------------------------------------------------------------------------------



string $before = "hoge";
string $after = "hoge";

string $node[] = `ls -type file`;
  
    for ($fileNode in $node){
  
        string $path = `getAttr ($fileNode + ".fileTextureName")`;
        print ($path + "\n") ;              
        string $changePath = `substitute $before $path $after`;
        print ($changePath + "\n") ;   
        setAttr -type "string" ($fileNode + ".fileTextureName") $changePath;
    }






2014年7月11日金曜日

メモ_maya(チャネル ボックスカラー)

ほかページからの転記

チャネル ボックス(Channel Box) カラー

ロックされている
グレー
キー設定不可
ライト グレー
ミュートされている
茶色
ブレンドされている
緑色
キー設定されている
明るいオレンジ色
エクスプレッション
紫色
コンストレイントされている
青色
接続済み
黄色


========================================================
Mel覚え書き
========================================================

--------------------------------------------------------
■for分テンプレート
--------------------------------------------------------
string $sentaku[] = ` ls -sl -tr ` ;
int $kazu = ` size ( $sentaku ) ` ;
int $x ;

for ( $x = 0 ; $x < $kazu ; $x++ )
{
string $locName = $sentaku[$x];
spaceLocator -n $locName;
}//for

--------------------------------------------------------
■指定した文字を含むオブジェクトをリスト
--------------------------------------------------------
ls "locator?"; 
ls "locator?""locator?2";//複数の文字列を指定する版 

↑結構簡単だった、、、。
「ls」コマンド後、「" "」で囲って文字列を指定するだけ。フラグもいらない。

--------------------------------------------------------
■文字列を置き換え(又は削除)
--------------------------------------------------------
string substituteAllString(string $text, string $searchStr, string $replaceStr)

$replaceStrを空の"" にすると削除と同じになる。

例:
string $text = "one + two + three + four";
string $result1 = substituteAllString($text, "+", "plus");
print $result1;

--------------------------------------------------------
■シーンのファイル名を調べる
--------------------------------------------------------
file -q -shortName -sceneName;

--------------------------------------------------------
■-typeフラグで使えるタイプを調べるコマンド
--------------------------------------------------------
ls -showType

--------------------------------------------------------
■アニメーションカーブを指定フレーム分ズラす
--------------------------------------------------------
string $animCurve[] = `ls -type animCurveTL -type animCurveTU -type animCurveTA -type animCurveTT`;
keyframe -edit -r -timeChange ( この括弧内にズラしたいフレーム数を記述してください ) $animCurve;

--------------------------------------------------------
■トランスフォームノードをリストUP
--------------------------------------------------------
ls -sl -typ transform;

--------------------------------------------------------
■ウィンドウ表示位置などをコントロールする
--------------------------------------------------------
windowPref -enableAll false;//多分、ウィンドウ作成時に強制されるデフォルト設定的なものを切ってる...。

//このコマンドで挟むようにウィンドウを作成する。

windowPref -enableAll true;//↑で切った設定をONに戻す



「-enableAll」フラグが何をしてるかは不明、、、。
(多分、ウィンドウ作成時に強制されるデフォルト設定的なものを切ってるんだと思う。)
「-w」や「-h」などのコマンドも機能するようになります。

--------------------------------------------------------
■ウィンドウにコメントなどのテキストを表示
--------------------------------------------------------
string $winName = "test";

windowPref -enableAll false;

if((`window -ex $winName`) == true)
deleteUI $winName;

window -w 360 -title $winName $winName;

scrollLayout;

text -al left//「left」、「right」、「center」の引数を指定する。

//-------------------------
"■テストコメント\n\
  test\n\
  test";
//-------------------------

showWindow;

windowPref -enableAll true;


--------------------------------------------------------
■可視性ONのパネルを検索→最後のパネルネームを取得
--------------------------------------------------------
string $panel[] = `getPanel -visiblePanels`;
int $kazu = `size($panel)`;
print $panel[($kazu - 1)];

※作成したモデルパネルの設定変更する際にパネルネームを取得して使用


--------------------------------------------------------
■論理演算子
--------------------------------------------------------
=====================================================
&& ~かつ・・・
|| ~または・・・("||"半角でshift+\で書ける。)
! ~じゃない
=====================================================

もし $num が0より大きくてかつ5以下であるなら…
という場合は

if(0 < $num && $num <= 5)
…

もし $num が0以下かまたは5より大きいなら
という場合は

if($num <= 0 || 5 < $num)
…

この様に書きます。

また、『~じゃなければ』という否定には、『!』記号を使います。

例えば、
if(!($num < 5))
…

この様に書くと、「もし$numが5より小さくなければ」という意味になります。



--------------------------------------------

int:整数型(整数のみ代入可能)
float:浮動小数点型(小数も代入可能)
string:文字列型(文字列を代入可能)

vector:ベクトルデータ型(3つの浮動小数点の組み合わせ)
配列型:同じ型の要素のリスト
matrix:行列型(2次元の表)

【↓例↓】
int $a = 10; 
float $b = 1.234; 
vector $v = <<1.2, 3.4, 6.5>>; 
※個々の値を参照するには、$v.x、$v.y、$v.zと記述する。
float $ar[] = {1.2, 3.4, 4.5}; // 浮動小数点の配列
matrix $mtx[3][2]; // 3*2の浮動小数点の表

■代入演算子

$x++ // $x = $x + 1と同じ意味。
$x-- // $x = $x - 1
$x += 5 // $x = $x + 5 
$x -= 3 // $x = $x - 3

■比較演算子

a == b // aはbと等しい
a != b // aはbと等しくない
a < b // aはb未満
a >= b // aはb以上である
a <= b // aはb以下である

■論理演算子

|| // or 
&& // and 
! // not 

--------------------------------------------




--------------------------------------------------------
■ウィンドウ作成
--------------------------------------------------------

{
/* 
「-exists」フラグは:指定した名前のウィンドウが存在するかどうかによってtrueまたはfalseを返します。
「if」コマンドでは( )の中の結果がTrueであればそれに続くコマンドを実行する。
*/

string $window = `window -title test aaa`;

if(`window -exists aaa`)
deleteUI aaa;

formLayout ;

button -label"ボタンの名前" ;

//window -title test aaa;
showWindow $window ;

}


string $kaz = 123 ;

if(`window -exists aaa`)
deleteUI aaa;

string $windowA = `window -title test aaa`;

//formLayout ;
columnLayout;
button -label "ボタン1" -command "print $kaz";

showWindow $windowA ;


window -title "レイアウト1";
columnLayout;
button -label "A";
rowLayout -numberOfColumns 2 -columnWidth2 20 20;
button -label "B";
button -label "C";
setParent ..;

/*
-numberOfColumn 2
横に何個の部品を並べるかを指定します。

-columnWidth2 20 20
各部品を並べる間隔の指定です。(2 個の場合) 
この場合、B・C ボタンがそれぞれ 20 ピクセル幅の範囲にレイアウトされます。 
3 個の部品を並べる場合には代わりに -columnWidth3 を使用します。

setParent ..;
rowLayout の有効範囲の終りです。 
これ以後は columnLayout が有効になるので、これ以降は部品が縦に並びます。
*/

button -label "D";
rowLayout -numberOfColumns 3 -columnWidth3 20 20 20;
button -label "E";
button -label "F";
button -label "G";
setParent ..;
showWindow;





//ボタンの間隔のパラメーター
int $cWibth = 20;

if(`window -ex XXX`)
deleteUI XXX;

string $winX = `window -title "kmoriyama" XXX`;
columnLayout;
button -label "A";

rowLayout -numberOfColumns 2 -columnWidth2 $cWibth $cWibth;
button -label "B";
button -label "C";
setParent ..;

rowLayout -numberOfColumns 3 -columnWidth3 $cWibth $cWibth $cWibth;
button -label "D";
button -label "E";
button -label "F";
setParent ..;

rowLayout -numberOfColumns 4 -columnWidth4 $cWibth $cWibth $cWibth $cWibth;
button -label "G";
button -label "H";
button -label "I" -w 20;
button -label "J";
setParent ..;

showWindow $winX;

========================================
アニムレイヤーを作成して、特定のリグを適用する
========================================

string $anmName = "Pose";

string $setRo = $anmName + ".rotationAccumulationMode" ;
string $setSc = $anmName + ".scaleAccumulationMode" ;

animLayer $anmName;

setAttr $setRo 0;
setAttr $setSc 1;

select -cl ;
select -r Rigroot Righara Rigkoshi Rigmune Rigkubi Rigatama Rigashi_RVec Rigashi_LVec Rigtekubi_LVec Rigtekubi_RVec Rigashi_RAll Rigashi_RReverse Rigtsumasaki_RReverse Rigtsumasaki_RDummy Rigashi_LAll Rigashi_LReverse Rigtsumasaki_LReverse Rigtsumasaki_LDummy ;

animLayer -e -addSelectedObjects -excludeScale -excludeDynamic -excludeBoolean -excludeEnum $anmName;

========================================
チャンネルボックスの余計なチャンネルの非表示
========================================
setAttr ノード名.ini 0;//これで非表示
setAttr ノード名.ini 2;//これで初期化。1ではないようです。

========================================
アニムカーブを検索してフレーム移動
========================================
int $StarFrame = `getAttr PRM.StartFrame`;
int $EndFrame = `getAttr PRM.EndFrame`;
int $LoopStart = `getAttr PRM.LoopStart`;
int $LoopEnd = `getAttr PRM.LoopEnd`;

string $animCurve[] = `ls -type animCurveTL -type animCurveTU -type animCurveTA -type animCurveTT`;
keyframe -edit -r -timeChange (-$LoopEnd) $animCurve;

playbackOptions -ast $StarFrame -aet ($EndFrame - $LoopEnd) -min $StarFrame -max ($EndFrame - $LoopEnd)

========================================
textフィールドウィンドウ
========================================
window;
columnLayout -adj true;
textField;
textFieldButtonGrp -label "ラベル" -text "textFieldButtonGrp" -buttonLabel "ボタン";
showWindow;


rowLayout -numberOfColumns 2;
button -label "<-StartOrEnd->" -w 102 -command "command7" ;

text -label "テストメッセージ";
separator -height 1 -style "double";
text -label "テストメッセージ";

========================================
選択したキーのアトリビュートネームをメモ帳に書き出す
========================================

//BlShapeのkeyを全て選択してく実行してください。
{
string $attName[] = `keyframe -q -name`;
$size = size($attName);

for($i=0; $i<$size; $i++){
string $FilePath = "C:/Users/k_moriyama.MEDIAV/Desktop/ぶれんどたーげっとリスト.txt"; //書き込み用テキストの場所指定
string $blnamea[] = `ls -typ blendShape`;
string $blnamea2 = $blnamea[0] + "_";
string $output = substituteAllString($attName[$i], $blnamea2 , "");
system("echo " + $output + ">> " + $FilePath);
}
print ("total = " + $size );
}

========================================
改行
========================================

string\n;// "\n"で改行

string $aaa = $attName[$i] + "\n";




例:

//BlShapeのkeyを全て選択してく実行してください。
{
string $attName[] = `keyframe -q -name`;
$size = size($attName);

for($i=0; $i<$size; $i++){
string $aaa = $attName[$i] + "\n";//MAYA上では"\"はスラッシュを逆のヤツになる。
print $aaa;
}
print ("total = " + $size );
}


========================================
.txtに書き込むmelSample
========================================

if(`window -q -exists TsTimeWindow`) deleteUI TsTimeWindow;

window TsTimeWindow;
columnLayout;
textFieldButtonGrp -bc "TsTimeCmd" -bl "OK" TsTimeTFG; //文末の"TsTimeTFG"はこのボタンの名称と思われ!

showWindow TsTimeWindow;

global proc TsTimeCmd(){
string $FilePath = "C:/Users/k_moriyama.MEDIAV/Desktop/test1.txt"; //書き込み用テキストの場所指定
string $time = `about -ct`; //多分、現在の時刻を取得して、変数に格納してる。
string $output = `textFieldButtonGrp -q -tx TsTimeTFG`; //"TsTimeTFG"という名前のフィールドの内容を"-q"を使って問い、取得してる。

system("echo " + $time + " " + $output + ">> " + $FilePath);
//deleteUI TsTimeWindow;
}

========================================
ボタン付ウィンドウテンプレ
========================================

//ウィンドウ、ボタン生成--------------------------------------------

string $windowName = "buttonWin" ; //ウィンドウ名はこの変数で指定してください。
string $windowTitle = "適当" ; //ウィンドウに表示するタイトルはこの変数で指定してください。


if(`window -exists $windowName`)
deleteUI $windowName;

window -w 100 -h 30 -title $windowTitle $windowName;
columnLayout;
button -label "ボタン1" -w 206 -command "command1";

rowLayout -numberOfColumns 4 ;
button -label "ボタン2" -w 50 -command "command2";
button -label "ボタン3" -w 50 -command "command3";
button -label "ボタン4" -w 50 -command "command4";
button -label "ボタン5" -w 50 -command "command5";


setParent ..;
rowLayout -numberOfColumns 2;

// button -label "ボタン6" -w 102 -command "timRangeCTRL" ;
button -label "ボタン7" -w 102 -command "select PRM" ;
button -label "ボタン8" -w 102 -command "command6" ;

setParent ..;

rowLayout -numberOfColumns 2;
button -label "ボタン9" -w 206 -command "command7" ;

setParent ..;


showWindow $windowName ;


//ボタンのコマンド生成--------------------------------------------

proc command1() //ボタン1
{
playblast -format avi -filename "C:/Users/k_moriyama.MEDIAV/Desktop/test1" -offScreen
-forceOverwrite -sequenceTime 0 -clearCache 1 -viewer 1 -showOrnaments 0 -fp 0 -percent 100 -compression "none" -quality 100 -widthHeight 1280 720;

}

proc command2() //ボタン2
{
print "コマンドを記述してください";
}

========================================
選択したオブジェクトのビジビリティをoff
========================================

string $sentaku[] = ` ls -sl -tr ` ;
int $kazu = ` size ( $sentaku ) ` ;
int $x ;

for ( $x = 0 ; $x < $kazu ; $x++ )
{
string $listShp[] = `listRelatives -s`;
string $visib = $listShp[$x] + ".visibility";
int $joutai = `getAttr $visib`;

if( $joutai == 1 )
{
setAttr $visib 0;
}
else
{
setAttr $visib 1;
}//elseのブロックエンド
}//forのブロックエンド

========================================
エクスプレッションMemo
========================================

================================================================================
■「基本的な記述の仕方」のメモ
================================================================================
joint1.translateZ = joint2.translateZ * 0.3;//ジョイント1(tz)にジョイント2の"tz*0.3"の値を代入

================================================================================
■指定フレーム数、遅れて追従するエクスプレッション
================================================================================
{
$ct = `currentTime -q`; //現在のフレーム位置
int $tm = 15; //遅れるフレーム数

if($ct >= $tm)
{
pSphere1.translateX = `getAttr -t ($ct - $tm) pCube1.tx`;
}
else
{
pSphere1.translateX = `getAttr -t 1 pCube1.tx`;
}
}



========================================
シェイプノードをペアレント
========================================
parent -shape -r;

※"シェイプノード"→"ペアレント先のトランスフォームノード"を選択して実行しないとエラーになる。


========================================
シェイプノード名取得
========================================
listRelatives -s;//選択されたオブジェクトのShapeノード名を取得する





========================================
選択されたオブジェクトのキーフレームの範囲とレンジの範囲を合わせる
========================================
selectKey -time ":";
float $allKeys[] = sort(`keyframe -q -sl`);
playbackOptions -min $allKeys[0] -max $allKeys[(size($allKeys) -1)];





========================================
シーン全体のアニメーションのキーを一括でオフセットする
========================================

global proc offsetAllAnimation(int $offsetVal)
{
string $animCurve[] = `ls -type animCurveTL -type animCurveTU -type animCurveTA -type animCurveTT`;
keyframe -edit -r -timeChange $offsetVal $animCurve;
}

animCurveの種類は、 input がTimeなら animCurveT(L U A T)
DrivenKeyのように  inputがDouble(数値)なら animCurveU(L U A T)
それぞれ、
L distance
A angle
T time
U double
の意味。
OffsetするのはDrivenKey以外のTimeと接続しているものなので animCurveT系のノードをリストし、
keyframe に -r(相対移動)のフラグを付ける。


========================================
文字列の置き換えコマンド
========================================
substituteっていうコマンドは

substitute A B C;

でBの文字列の中にあるAという文字列をCで置き換えるというコマンドです。

A:"B"内をこの文字列で検索する
B:置き換え対象の文字列
C:この文字列に置き換える



========================================
ボタンのサイズをウィンドウにあわせる
========================================
例: rowLayout -numberOfColumns 4 -adjustableColumn 1;//横にボタンを並べるレイアウト

レイアウトに「-adjustableColumn 1」フラグをつける。0で多分off。


========================================
実行するたびにon/offを切り替える書き方
========================================
setAttr time1.enableTimewarp (!`getAttr time1.enableTimewarp`);

・多分()内で、取得した数値を[!]コマンド?で反転することでon⇔off切り替えを実現している。
・一行で済むから美しい!


========================================
チェックボックスの状態を取得
========================================
string $checkBox1 = `checkBox -label "スケールX"`;//チェックボックスは変数に格納する
if(`checkBox -q -value $checkBox1`)//チェックボックスの状態[-value]を[-q]で取得してonならif実行
{
print "チェックボックスのチェックがonなら実行"
}


========================================
アトリビュートがノード上に存在を確認(attributeExistsコマンド)
========================================
基本: attributeExists("attributeName","nodeName")

例: if (attributeExists("visibility","mySphere")) {
setAttr mySphere.visibility on;
}

・指定のノードに指定したアトリビュートが存在するかを確認できます。


========================================
サイズ、位置などを復元しない
========================================
windowPref -remove $WindowName このコマンドを実行することで復元をやめさせることができる。
「showWindow」の前に実行させる。

windowPref -enableAll false ┬このコマンドでウィンドウ生成コマンドを挟む
windowPref -enableAll true ┘


========================================
ファイルに書き出す
========================================

$exampleFileName = "C:/Users/k_moriyama.MEDIAV/Desktop/test1.txt";//ファイルパスを変数に格納
$fileId=`fopen $exampleFileName "w"`;//ファイル識別子を変数に格納

/*
■識別子の種類↓
"w" 書き込み用のファイルを開く(ファイルの以前の内容を破棄する)
"a" 書き込み用にアペンドする(ファイルの最後にアペンドする)
"r" 読み取り用に開く
*/

fprint $fileId "書き込みたい文字列(変数指定可)";
fclose $fileId;//終了する